I have a JUnit 4 test which creates test data and asserts the test condition for every single data. If everything is correct, I get a green test.
If one data fails the test, the execution of the whole test is interrup开发者_StackOverflow中文版ted. I would like to have a single JUnit test for each data. Is it possible to spawn JUnit tests programmatically, so that I get a lot of tests in my IDE?
The reason for this approach is to get a quicker overview which test fails and to continue the remaining tests, if one data fails.
It sounds like you'd want to write a parameterized test (that does the exact same checks on different sets of data).
There's the Parameterized
class for this. This example shows how it can be used:
@RunWith(Parameterized.class)
public class FibonacciTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {{ 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
}
private final int input;
private final int expected;
public FibonacciTest(final int input, final int expected) {
this.input = input;
this. expected = expected;
}
@Test
public void test() {
assertEquals(expected, Fibonacci.compute(input));
}
}
Note that the data()
method returns the data to be used by the test()
method. That method could take the data from anywhere (say a data file stored with your test sources).
Also, there's nothing that stops you from having more than one @Test
method in this class. This provides an easy way to execute different tests on the same set of parameters.
精彩评论