天天看點

Eclipse中使用Junit編寫測試用例

  在項目中添加junit庫

  在編寫測試用例之前,需要先引入junit。對項目根目錄右鍵,選擇properties,java build path,libraries,如圖:

Eclipse中使用Junit編寫測試用例

  add library,選擇junit:

Eclipse中使用Junit編寫測試用例

  點next選擇junit版本,然後finish就完成了引入。

  編寫測試用例

  假設有如下類:

  package choon.test;

  public class calculate {

  public int  add(int x,int y) {

  return x + y;

  }

  可以編寫測試用例如下:

package choon.test;

import static org.junit.assert.*;

import org.junit.test;

public class test1 {

@test

calculate calculate = new calculate();

assertequals(8, calculate.add(3, 5));

}

  對test方法右鍵run as junit test即可運作該測試用例:

Eclipse中使用Junit編寫測試用例

  如圖,綠色狀态條表示測試通過,如果是紅色,則表示沒有通過。

before和after标簽

  被before标記的方法在每個測試用例執行之前執行,被after标記的方法在每個測試用例執行後執行。

  假如編寫如下測試用例:

import org.junit.after;

import org.junit.before;

@before

public void setup() {

system.out.println("---begin test---");

public void test() {

system.out.println("test case");

@after

public void teardown() {

system.out.println("---end test---");

  則會有下面的執行結果:

Eclipse中使用Junit編寫測試用例

  測試用例的編寫很重要,一個不好的測試用例既起不到測試作用又浪費時間,而一個好的測試用例可以很好的指出代碼中的問題,避免更大的麻煩。

最新内容請見作者的github頁:http://qaseven.github.io/

繼續閱讀