您的位置:软件测试 > 开源软件测试 > 开源单元测试工具 > junit
Eclipes使用Junit进行测试
作者:陌然之始 发布时间:[ 2017/3/23 17:03:00 ] 推荐标签:单元测试 Junit

  任务一,Install Junit(4.12), Hamcrest(1.3) with Eclipse
  首先在网上下载Junit和Hamcrest的jar文件,Right click on the project root directory - > build path - > configure build path - > library the junit. Jar, hamcrest. Jar added
  任务二,Install Eclemma with Eclipse
  在myeclipse顶部菜单栏中 help->install from catalog,在搜索栏中输入Eclemma,点击安装,一步步按照提示,即可完成安装
  任务三,Write a java program for the triangle problem and test the program with Junit.
  a) Description of triangle problem:
Function triangle takes three integers a,b,c which are length of triangle sides; calculates whether the triangle is equilateral, isosceles, or scalene.
progran:
package hw1;
public class exp {
public int trian(int a,int b,int c){
if((a==b)&&(a==c)&&(b==c)){  //等边三角形
return 0;
}
else if((a != b)&&(a!=c)&&(b!=c)){  //不等边三角形
return 1;
}
else{
return 2;      //等腰三角形
}
}
}
  b)Using junit test
  打开eclipse,点击左上角的File,新建一个Java project,命名为hello,然后在src目录下新建两个包,分别命名为hw1和test。
  在hw1中新建一个class,命名为exp.java.
  在exp.java中输入如下代码:

  然后右击exp.java,在选项new里面点击JUnit Test Case,点击next。
  新建了expTest.java后,将两个方法里面的“fail("Not yet implemented");”删去,加入如下代码:
package test;
import java.util.Arrays;
import java.util.Collection;
import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import hw1.exp;
import static org.junit.Assert.*;
@RunWith(Parameterized.class) //这是一个参数化的测试类
public class expTest {
private exp tr;
private int a,b,c,expected;
public expTest(int a,int b,int c,int expected){
this.a=a;
this.b=b;
this.c=c;
this.expected=expected;
}
@Before   //在运行之前先运行这个函数
public void setUp(){
tr=new exp();
}
@Parameters  //给构造函数参数初始化
public static Collection<Object[]> getData(){
return Arrays.asList(new Object[][]{
{1,2,3,1},
{2,2,2,0},
{2,2,3,2},
{2,3,4,1}
});
}
@Test     //测试Train函数
public void testTrian(){
assertEquals(this.expected,tr.trian(a,b,c));
}
}
  保存后,右击expTest.java,选择Run As,再选择Junit Test,即可运行junit,测试在ScoreTest.java里面的数据是否正确。如图,测试结果通过则显示绿条,否则显示红条,可以根据提示找到错误所在

  测试正确,使用junit进行程序测试,会发现非常方便,很容易找到哪里出错。

软件测试工具 | 联系我们 | 投诉建议 | 诚聘英才 | 申请使用列表 | 网站地图
沪ICP备07036474 2003-2017 版权所有 上海泽众软件科技有限公司 Shanghai ZeZhong Software Co.,Ltd