您的位置:首页 > 其它

软件测试——Junit的使用

2016-03-18 14:16 381 查看
  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里。

package lab1;

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 Lab1Test {

private int input1;
private int input2;
private int input3;
private String expected;
private Lab1 test;

public Lab1Test(int input1,int input2,int input3, String expected){
this.input1 = input1;
this.input2 = input2;
this.input3 = input3;
this.expected = expected;
}

@Before
public void setUp(){
test = new Lab1();
}

@Parameters
public static Collection<Object[]> getData(){
return Arrays.asList(new Object[][]{
{2, 3, 4, "一般三角形"},
{4, 7, 9, "一般三角形"},
{5, 5, 5, "等边三角形"},
{1, 1, 1, "等边三角形"},
{6, 7, 7, "等腰三角形"},
{4, 7, 4, "等腰三角形"},
{2, 2, 3, "等腰三角形"},
{1, 6, 4, "输入的边不能构成三角形"},
{0, -1, 3, "输入的边不能构成三角形"},
});
}

@Test
public void testCheck() {
assertEquals(this.expected, test.check(input1, input2, input3));
}
}


  Run As -- Junit Test即可看到每个用例的结果:

  


  附上Lab1的check():

public String check( int a, int b, int c){
//排序使a<=b<=c
int temp;
if( a > b){
if( a > c){
temp = c;
c = a;
if( b > temp)
a = temp;
else{
a = b;
b = temp;
}
}else{
temp = a;
a = b;
b = temp;
}
}else if( b > c){
temp = c;
c = b;
b = temp;
}

if( a <= 0 || a + b <= c)
return "输入的边不能构成三角形";
else if (a == b || b == c)
return a == c ? "等边三角形" : "等腰三角形";
else
return "一般三角形";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: