您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > junit
Eclipes使用Junit進(jìn)行測試
作者:陌然之始 發(fā)布時間:[ 2017/3/23 17:03:00 ] 推薦標(biāo)簽:單元測試 Junit

  任務(wù)一,Install Junit(4.12), Hamcrest(1.3) with Eclipse
  首先在網(wǎng)上下載Junit和Hamcrest的jar文件,Right click on the project root directory - > build path - > configure build path - > library the junit. Jar, hamcrest. Jar added
  任務(wù)二,Install Eclemma with Eclipse
  在myeclipse頂部菜單欄中 help->install from catalog,在搜索欄中輸入Eclemma,點擊安裝,一步步按照提示,即可完成安裝
  任務(wù)三,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) //這是一個參數(shù)化的測試類
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   //在運(yùn)行之前先運(yùn)行這個函數(shù)
public void setUp(){
tr=new exp();
}
@Parameters  //給構(gòu)造函數(shù)參數(shù)初始化
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函數(shù)
public void testTrian(){
assertEquals(this.expected,tr.trian(a,b,c));
}
}
  保存后,右擊expTest.java,選擇Run As,再選擇Junit Test,即可運(yùn)行junit,測試在ScoreTest.java里面的數(shù)據(jù)是否正確。如圖,測試結(jié)果通過則顯示綠條,否則顯示紅條,可以根據(jù)提示找到錯誤所在

  測試正確,使用junit進(jìn)行程序測試,會發(fā)現(xiàn)非常方便,很容易找到哪里出錯。

軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd