單元測試

文章目錄

Junit

  • @Runwith
    • 用來指定以何種方式運行 @Test
    • MockitoJUnitRunner.class 不用啓動程序環境即可開始 @Test
    • SpringRunner.class 一般在需要模擬程序的虛擬環境的時候用,會啓動項目的環境,會比較慢。經常和 @SpringbootTest 一起使用。也可以使用 @Autowired 將要測試的對象引進來,就像平常的業務類一樣使用就好。
    • Parameterized.class 參數化測試,可以模擬多個參數調用同一段代碼但不同參數的方法,並輸出結果。可以參考網址:
      CSDN-單元測試~JUnit4 參數化測試官方參數化測試介紹
import static org.junit.Assert.assertEquals;

import java.util.Arrays;

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 FibonacciTest {

    @Parameters(name = "{index}: fib({0})={1}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][] { 
                 { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }
           });
    }

    private int input;
    private int expected;

    public FibonacciTest(int input, int expected) {
        this.input = input;
        this.expected = expected;
    }

    @Test
    public void test() {
        assertEquals(expected, Fibonacci.compute(input));
    }
}

public class Fibonacci {
    ...
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章