(注意,我要用官方文檔開始刷存在感了…)
Junit通過自定義runner——Parameterized來實現參數化測試,參數化測試主要用于需要重復測試不同條件的場景,舉個栗子:
public class Fibonacci {
public static int compute(int n) {
int result = 0;
if (n <= 1) {
result = n;
} else {
result = compute(n - 1) + compute(n - 2);
}
return result;
}
}
對于Fibonacci的compute函數,為了保證測試覆蓋率,需要提供不同n值并驗證其結果,采用一般的寫法,需要寫很多的assert,而借助Parameterized則很方便。如:
import static org.junit.Assert.assertEquals;
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 FibonacciTest {
@Parameters
public static Collection data() {
return Arrays.asList(new Object[][] {
{ 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }
});
}
private int fInput;
private int fExpected;
public FibonacciTest(int input, int expected) {
fInput= input;
fExpected= expected;
}
@Test
public void test() {
assertEquals(fExpected, Fibonacci.compute(fInput));
}
}
Junit會使用FibonacciTest的兩參數構造方法及@Parameters注解的數據初始化FibonacciTest實例,并運行測試用例。
這里需要注意,由于Parameterized的原理是多次構造測試用例類的實例并運行測試用例,假如此測試用例中還存在其它測試方法(除去test),則它們也會被多次調用。所以合理的使用應該是為Parameterized建立獨立的測試用例類。
前面的栗子中使用了構造函數來注入,還可以使用Junit提供的@Parameter注解,如:
import static org.junit.Assert.assertEquals;
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.Parameter;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class FibonacciTest {
@Parameters
public static Collection data() {
return Arrays.asList(new Object[][] {
{ 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }
});
}
@Parameter // first data value (0) is default
public /* NOT private */ int fInput;
@Parameter(value = 1)
public /* NOT private */ int fExpected;
@Test
public void test() {
assertEquals(fExpected, Fibonacci.compute(fInput));
}
}
如果你嘗試過運行上面的測試用例,就會發現測試用例的名稱沒有任何辨識度,可能就是一串連續的數字。為了更好的識別每個參數化的測試用例,可以選擇通過占位符的方式來為它們命名,其規則為:
{index}:當前的參數索引;
{0},{1},{2},…:第一,第二,第三個參數,以此類推;
一個栗子:
@RunWith(Parameterized.class)
public class FibonacciTest {
@Parameters(name = "{index}: fib({0})={1}")
public static Iterable 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));
}
}
如果未說明,本Blog中文章皆為原創文章,請尊重他人勞動,轉載請注明:轉載自jmatrix
本文鏈接地址: Junit4:參數化測試
原文轉自: http://www.jmatrix.org/java/translation/1156.html