是否可以使用JUnitCore API運行參數化測試類?使用JUnitCore運行參數化測試
我已經在測試一個類中調用斐波納契,稱爲TestFibonacci一個參數測試類,和一個簡單的Java類(JUnitParameterized),它執行使用JUnitCore API的TestFibonacci類。如果我使用JUnit插件或命令行執行TestFibonacci,它會通過。但是,當我使用我的JUnitParameterized類執行它時,它會失敗。
類被測
public class Fibonacci {
public static int compute(int n) {
if (n <= 1) {
return n;
}
return compute(n-1) + compute(n-2);
}
}
測試類
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
@RunWith(Parameterized.class)
public class TestFibonacci {
@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 TestFibonacci(int input, int expected) {
this.input = input;
this.expected = expected;
}
@Test
public void test() {
assertEquals(expected, Fibonacci.compute(input));
}
}
Java程序
import org.junit.runner.JUnitCore;
import org.junit.runner.Request;
import org.junit.runner.Result;
public class JUnitParameterized {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> testClass = JUnitParameterized.class.getClassLoader().loadClass(TestFibonacci.class.getCanonicalName());
Result result = (new JUnitCore()).run(Request.method(testClass, "test"));
System.out.println("Number of tests run: " + result.getRunCount());
System.out.println("The number of tests that failed during the run: " + result.getFailureCount());
System.out.println("The number of milliseconds it took to run the entire suite to run: " + result.getRunTime());
System.out.println("" + (result.wasSuccessful() == true ? "Passed :)" : "Failed :("));
}
}
非常感謝斯捷潘。 :) – josecampos