一、junit、hamcrest和eclemma的安装。
1.junit和hamcrest在新建了junitHw1工程后在build path里通过add external jars添加junit-4.12.jar和hamcrest-all-1.3.jar。
2.eclemma在eclipse下点击help-eclipse marketplace-find-eclemma安装。
二、编写Triangle以及TestTriangle1。
1.Triangle-判断三角形类型
public static String whatIsTriangle(double a,double b, double c){ if(a <= 0 || b <= 0 || c <= 0) return "wrong"; if(a + b > c && a + c > b && b + c > a){ if(a == b && a ==c) return "equilateral"; else if(a==b || a==c || b==c) return "isosceles"; else return "scalene"; } else{ return "wrong"; } }
将方法写为静态方法,方便方法的调用。
2.TestTriangle1
package cn.tju.scs.lyz; import static org.junit.Assert.*; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class TestTriangle1 { private double input1; private double input2; private double input3; private String expected; public TestTriangle1(double input1,double input2,double input3,String expected){ this.input1 = input1; this.input2 = input2; this.input3 = input3; this.expected = expected; } @Parameters public static Collection<Object[]> getData(){ return Arrays.asList(new Object[][]{ {3,3,3,"equilateral"}, {3,4,3,"isosceles"}, {3,4,5,"scalene"}, {0,0,0,"wrong"}, {1,3,4,"wrong"} }); } @Test public void test(){ assertEquals(this.expected,Triangle.whatIsTriangle(input1,input2,input3)); } }
三、测试结果
五个测试用例均通过。
覆盖程度上图,TestTriangle1的覆盖率为100%。