软件测试:lab1.Junit and Eclemma
Task:
- Install Junit(4.12), Hamcrest(1.3) with Eclipse
- Install Eclemma with Eclipse
- Write a java program for the triangle problem and test the program with Junit.
a) Description of triangle problem:
Function triangle takes three integers a,b,c which are length of triangle sides; calculates whether the triangle is equilateral, isosceles, or scalene.
Report:
Junit:http://mvnrepository.com/artifact/junit/junit/4.12
Hamcrest:http://mvnrepository.com/artifact/org.hamcrest/hamcrest-all/1.3
Eclemma:https://sourceforge.net/projects/eclemma/
1. Junit(4.12), Hamcrest(1.3)安装与配置
eclipse中新建Java项目scs2015,再在该项目下新建目录lib,将hamcrest-all-1.3.jar,junit-4.12.jar拷贝到lib目录下,并导入项目里;
2. Eclemma的安装与配置
eclipse中—点击Help菜单—Install New Software,在弹出的对话框中,点击Add,之后点击 Archive,找到你下载好的 Eclemma.zip 资源文件,按照提示一步一步的安装重新启动 eclipse就完成了;
3. Test triangle program with Junit
点击安装Eclemma后工具栏上新增的覆盖测试按钮,来使用Eclemma测试Java程序
测试结果如上图所示。
在 Java 编辑器中,EclEmma 用不同的色彩标示了源代码的测试情况。其中,绿色的行表示该行代码被完整的执行,红色部分表示该行代码根本没有被执行,而黄色的行表明该行代码部分被执行。黄色的行通常出现在单行代码包含分支的情况,例如上图中的 20 行就显示为黄色。
除了在源代码编辑窗口直接进行着色之外,EclEmma 还提供了一个单独的视图来统计程序的覆盖测试率。
由于Triangle.java中还有一些get set 方法行没有被测试覆盖,上图Coverage为52.6%,尝试删去多余代码行后视图显示如下:
代码附录:
Triangle.java
public class Triangle { private double side1,side2,side3; public Triangle(double side1, double side2, double side3) { super(); this.side1 = side1; this.side2 = side2; this.side3 = side3; } public String getShape() { String sha[]= {"equilateral","isosceles", "scalene"}; int i=-1; if(this.side1!=this.side2&&this.side1!=this.side3&&this.side2!=this.side3) { i=2; }else if(this.side1==this.side2&&this.side2==this.side3) { i=0; }else { i=1; } return sha[i]; } }
TriangleTest.java
public class TriangleTest { @Test public void testEquilateral() { double a1=1,a2=1,a3=1; Triangle tria=new Triangle(a1, a2, a3); assertEquals("equilateral",tria.getShape()); } @Test public void testIsosceles() { double b1=1,b2=1,b3=1.2; Triangle trib=new Triangle(b1, b2, b3); assertEquals("isosceles",trib.getShape()); } @Test public void testScalene() { double c1=3,c2=4,c3=5; Triangle tric=new Triangle(c1, c2, c3); assertEquals("scalene",tric.getShape()); } }