Lab1:Junit and Eclemma
a)安装junit和hamcrest:
在网上搜素并下载junit-4.12.jar 和 hamcrest-core-1.3.jar 两个jar包,在项目里创建一个lib文件夹将jar包放进去,再右键选择这两个jar包,选择Build Path->add to build path 即可。
安装eclemma:
点击eclipse的help,选择eclipse marketplace, 在find框里搜索eclemma并按照指示安装即可。
b)本次实验要实现一个三角形问题并测试,根据输入的三条边长度判断是否是等边、等腰或不等边三角形。实现代码如下:
package com.triangle; public class Triangle { public String testTriangle(double a, double b, double c) { if (a + b > c && a + c > b && b + c > a) { if (a == b && b == c) { return "equilateral"; } else if (a != b && b != c && a != c) { return "scalene"; } else return "isosceles"; } else return "not a triangle"; } }
对里面的方法建立junit测试类,代码如下:
package com.triangle; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Collection; import org.junit.Before; 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 TriangleTest { private double a; private double b; private double c; private String expected; private Triangle t; @Before public void setUp() throws Exception { t = new Triangle(); } public TriangleTest(double a, double b, double c, String expected) { this.a = a; this.b = b; this.c = c; this.expected = expected; } @Parameters public static Collection<Object[]> getData() { return Arrays.asList(new Object[][] { { 1, 1, 2, "not a triangle" }, { 2, 3, 2, "isosceles" }, { 3, 3, 3, "equilateral" }, { 3, 4, 5, "scalene" } }); } @Test public void testTestTriangle() { assertEquals(this.expected, t.testTriangle(a, b, c)); } }
这样可以一次性测试多个测试用例,我分别设置了四种情况,测试结果如下: