Junit測試套件及參數化設置

一、測試套件

測試套件是用來批量測試類的,即使用@RunWith(Suite.class)將一個類修飾成測試套件類,該類中不能含有任何內容。

首先新建3個測試類,代碼如下:

public class Test1 { //第一個測試類
    @Test
    public void test() {
        System.out.println("test1");
    }
}

public class Test2 {  //第二個測試類
    @Test
    public void test() {
        System.out.println("test2");
    }
}

public class Test3 {  //第三個測試類
    @Test
    public void test() {
        System.out.println("test3");
    }
}

然後建立一個測試套件的入口類,不包含任何方法,更改測試運行器Suite.class,將要被測試的類作爲數組傳入到SuiteClasses,代碼如下:

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({Test1.class,Test2.class,Test3.class})
public class SuiteTest {
    //不能包含任何內容
}

二、參數化設置

步驟一:新建一個測試類,使用@RunWith(Parameterized.class)聲明爲參數設置類

步驟二:在類中定義用來存放預期值和輸入參數的變量,並構造方法

步驟三:測試多組數據就需要用數組進行返回,所以可以定義一個Collection類型的靜態方法,需要使用@parameters註解

步驟四:寫一個測試方法

代碼如下:

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 {
    int expected = 0;
    int input1 = 0;
    int input2 = 0;

    public ParameterTest(int expected,int input1,int input2){
        this.expected = expected;
        this.input1 = input1;
        this.input2 = input2;
    }

    @Parameters
    public static Collection<Object[]> t(){
        return Arrays.asList(new Object[][]{
                {3,1,2},{5,2,3}
        });
    }

    @Test
    public void testAdd(){
        assertEquals(expected,new Number().add(input1, input2));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章