Eclipes使用Junit进行测试

发表于:2017-3-23 11:40

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:陌然之始    来源:51Testing软件测试网采编

  任务一,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进行程序测试,会发现非常方便,很容易找到哪里出错。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号