软件测试——Junit的使用
Junit是一个很方便易用的软件测试工具,这里以测试检测三角形是等腰、等边还是一般三角形的方法为例,介绍Junit的用法。
1.安装配置
在Build Path添加junit-4.12.jar和hamcrest-all-1.3.jar,新建Junit Test Case,选择test文件夹,并保持其他路径一致。
如遇到No Junit tests found错误,请右键test文件夹,选择Build Path--Use as source folder.
2.编写用例并测试
使用assertEquals(excepted, actual)进行测试,将测试用例存储在Collection里。
1 package lab1; 2 3 import static org.junit.Assert.assertEquals; 4 import java.util.Arrays; 5 import java.util.Collection; 6 7 import org.junit.Before; 8 import org.junit.Test; 9 import org.junit.runner.RunWith; 10 import org.junit.runners.Parameterized; 11 import org.junit.runners.Parameterized.Parameters; 12 13 @RunWith(Parameterized.class) 14 public class Lab1Test { 15 16 private int input1; 17 private int input2; 18 private int input3; 19 private String expected; 20 private Lab1 test; 21 22 public Lab1Test(int input1,int input2,int input3, String expected){ 23 this.input1 = input1; 24 this.input2 = input2; 25 this.input3 = input3; 26 this.expected = expected; 27 } 28 29 @Before 30 public void setUp(){ 31 test = new Lab1(); 32 } 33 34 @Parameters 35 public static Collection<Object[]> getData(){ 36 return Arrays.asList(new Object[][]{ 37 {2, 3, 4, "一般三角形"}, 38 {4, 7, 9, "一般三角形"}, 39 {5, 5, 5, "等边三角形"}, 40 {1, 1, 1, "等边三角形"}, 41 {6, 7, 7, "等腰三角形"}, 42 {4, 7, 4, "等腰三角形"}, 43 {2, 2, 3, "等腰三角形"}, 44 {1, 6, 4, "输入的边不能构成三角形"}, 45 {0, -1, 3, "输入的边不能构成三角形"}, 46 }); 47 } 48 49 @Test 50 public void testCheck() { 51 assertEquals(this.expected, test.check(input1, input2, input3)); 52 } 53 }
Run As -- Junit Test即可看到每个用例的结果:
附上Lab1的check():
1 public String check( int a, int b, int c){ 2 //排序使a<=b<=c 3 int temp; 4 if( a > b){ 5 if( a > c){ 6 temp = c; 7 c = a; 8 if( b > temp) 9 a = temp; 10 else{ 11 a = b; 12 b = temp; 13 } 14 }else{ 15 temp = a; 16 a = b; 17 b = temp; 18 } 19 }else if( b > c){ 20 temp = c; 21 c = b; 22 b = temp; 23 } 24 25 if( a <= 0 || a + b <= c) 26 return "输入的边不能构成三角形"; 27 else if (a == b || b == c) 28 return a == c ? "等边三角形" : "等腰三角形"; 29 else 30 return "一般三角形"; 31 }