天天看點

Junit技巧

測試套件:

@RunWith(Suite.class)
@Suite.SuiteClasses({TaskTest1.class, TaskTest2.class, TaskTest3.class})
public class SuiteTest{
       
}      

//測試套件就是組織測試類一起運作,這個類裡不包含其它方法,将要測試的類作為數組傳入到Suite.SuiteClasses修飾符中。

@Test(timeout=毫秒)  @Test(expected=異常類  xxxException.class)

@Ignore 所修飾的測試方法會被測試運作器忽略,可以加上注釋資訊@Ignore("該類無效")

@RunWith: 可以修改測試運作器 org.junit.runner.Runner

@BeforeClass: 修飾的方法會在其它的方法運作前被執行,該方法需被static修飾,整個測試類運作期間,隻執行一次。

@AfterClass: 修飾的方法會在其它的方法運作結束後被執行,該方法需被static修飾,整個測試類運作期間,隻執行一次。

@Before:會在每一個測試方法被運作前執行一次,運作期間執行次數等同于測試方法數。

@After 會在每個測試方法被運作後執行一次,運作期間執行次數等同于測試方法數。

假設有一個方法計算兩數之和,我們一次測試多個用例時,可以使用以下方法:

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class ParameterTest {
    /*
     * 1.更改預設的測試運作器為RunWith(Parameterized.class)
     * 2.聲明變量來存放預期值 和結果值
     * 3.聲明一個傳回值 為Collection的公共靜态方法,并使用@Parameters進行修飾
     * 4.為測試類聲明一個帶有參數的公共構造函數,并在其中為之聲明變量指派
     */
    int expected =0;
    int input1 = 0;
    int input2 = 0;
    
    @Parameters
    public static Collection<Object[]> t() {
        return Arrays.asList(new Object[][]{
                {3,1,2},
                {4,2,2}
        }) ;
    }
    
    public ParameterTest(int expected,int input1,int input2) {
        this.expected = expected;
        this.input1 = input1;
        this.input2 = input2;
    }
    
    @Test
    public void testAdd() {
        assertEquals(expected, new Calculate().add(input1, input2));
    }

}      

繼續閱讀