您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > junit
JUnit4概述(一)
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 2013/12/9 10:30:24 ] 推薦標(biāo)簽:

JUnit4是JUnit框架有史以來的大改進(jìn),其主要目標(biāo)便是利用Java5的Annotation特性簡化測試用例的編寫。

先簡單解釋一下什么是Annotation,這個單詞一般是翻譯成元數(shù)據(jù)。元數(shù)據(jù)是什么?元數(shù)據(jù)是描述數(shù)據(jù)的數(shù)據(jù)。也是說,這個東西在Java里面可以用來和public、static等關(guān)鍵字一樣來修飾類名、方法名、變量名。修飾的作用描述這個數(shù)據(jù)是做什么用的,差不多和public描述這個數(shù)據(jù)是公有的一樣。想具體了解可以看Core    Java2。廢話不多說了,直接進(jìn)入正題。

我們先看一下在JUnit 3中我們是怎樣寫一個單元測試的。比如下面一個類:
public class AddOperation {
      public int add(int x,int y){
          return x+y;
      }
}

我們要測試add這個方法,我們寫單元測試得這么寫:
import junit.framework.TestCase;
import static org.junit.Assert.*;
public class AddOperationTest extends TestCase{

      public void setUp() throws Exception {
      }

      public void tearDown() throws Exception {
      }

      public void testAdd() {
          System.out.println("add");
          int x = 0;
          int y = 0;
          AddOperation instance = new AddOperation();
          int expResult = 0;
          int result = instance.add(x, y);
          assertEquals(expResult, result);
      }
}

可以看到上面的類使用了JDK5中的靜態(tài)導(dǎo)入,這個相對來說很簡單,只要在import關(guān)鍵字后面加上static關(guān)鍵字,可以把后面的類的static的變量和方法導(dǎo)入到這個類中,調(diào)用的時候和調(diào)用自己的方法沒有任何區(qū)別。


我們可以看到上面那個單元測試有一些比較霸道的地方,表現(xiàn)在:
1.單元測試類必須繼承自TestCase。
2.要測試的方法必須以test開頭。

如果上面那個單元測試在JUnit 4中寫不會這么復(fù)雜。代碼如下:
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

/**
*
* @author bean
*/
public class AddOperationTest extends TestCase{
  
      public AddOperationTest() {
      }

      @Before
      public void setUp() throws Exception {
      }

      @After
      public void tearDown() throws Exception {
      }

      @Test
      public void add() {
          System.out.println("add");
          int x = 0;
          int y = 0;
          AddOperation instance = new AddOperation();
          int expResult = 0;
          int result = instance.add(x, y);
          assertEquals(expResult, result);
      }
  
}

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