1.导入 JUnit,Hamcrest
Project -> Properites -> Java Build Path -> Add External JARs
2. 安装 Eclemma
Help -> Eclipse marketplace
搜索 Eclemma,点击Installed
3. 测试代码
TrianglePractice:
public class TrianglePractice {
public TriangleType triangle(int a, int b, int c) {
if (a+b<=c || a+c<=b || b+c<=a) return TriangleType.not_triangle;
if (a==b) {
if (b==c) return TriangleType.equilateral;
else return TriangleType.isosceles;
} else {
if (b==c || a==c) return TriangleType.isosceles;
else return TriangleType.scalene;
}
}
}
TriangleType:
public enum TriangleType {
not_triangle,equilateral,isosceles,scalene
}
TrianglePracticeTest:
import static org.junit.Assert.*;
import java.util.*;
import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class TrianglePracticeTest {
private TrianglePractice t=null;
private int a,b,c;
private TriangleType expected;
public TrianglePracticeTest(List<Integer> list, TriangleType type) {
a=list.get(0);
b=list.get(1);
c=list.get(2);
expected=type;
}
@Before
public void setUp() {
t=new TrianglePractice();
}
@Parameters
public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{Arrays.asList(new Integer[]{2,2,2}),TriangleType.equilateral},//Path:1,3,4,6
{Arrays.asList(new Integer[]{1,1,1}),TriangleType.equilateral},
{Arrays.asList(new Integer[]{2,2,3}),TriangleType.isosceles},//Path:1,3,4,7
{Arrays.asList(new Integer[]{2,2,1}),TriangleType.isosceles},
{Arrays.asList(new Integer[]{2,3,2}),TriangleType.isosceles},//Path:1,3,5,8
{Arrays.asList(new Integer[]{2,3,3}),TriangleType.isosceles},
{Arrays.asList(new Integer[]{2,3,4}),TriangleType.scalene},//Path:1,3,5,9
{Arrays.asList(new Integer[]{1,1,2}),TriangleType.not_triangle},//Path:1,2
{Arrays.asList(new Integer[]{2,2,4}),TriangleType.not_triangle},
{Arrays.asList(new Integer[]{2,3,6}),TriangleType.not_triangle},
}
);
}
@Test
public void test() {
assertEquals(t.triangle(a, b, c), expected);
}
}
4. JUnit 测试结果
5. Eclemma 覆盖结果