是否可以使用 JUnitCore API 运行参数化测试类?
我有一个名为Fibonacci的测试类,一个名为TestFibonacci的参数化测试类,以及一个使用 JUnitCore API执行TestFibonacci类的简单 Java 类 ( JUnitParameterized )。如果我使用 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 :("));
}
}