Running the same JUnit test case multiple time with different data

Is there there any way to tell JUnit to run a specific test case multiple times with different data continuously before going on to the next test case?

75582 次浏览

I always just make a helper method that executes the test based on the parameters, and then call that method from the JUnit test method. Normally this would mean a single JUnit test method would actually execute lots of tests, but that wasn't a problem for me. If you wanted multiple test methods, one for each distinct invocation, I'd recommend generating the test class.

It sounds like that is a perfect candidate for parametrized tests.

But, basically, parametrized tests allow you to run the same set of tests on different data.

Here are some good blog posts about it:

take a look to junit 4.4 theories:

import org.junit.Test;
import org.junit.experimental.theories.*;
import org.junit.runner.RunWith;


@RunWith(Theories.class)
public class PrimeTest {


@Theory
public void isPrime(int candidate) {
// called with candidate=1, candidate=2, etc etc
}


public static @DataPoints int[] candidates = {1, 2, 3, 4, 5};
}

Here is a post I wrote that shows several ways of running the tests repeatedly with code examples:

Run a JUnit test repeatedly

You can use the @Parametrized runner, or use the special runner included in the post

Recently I started zohhak project. It lets you write:

@TestWith({
"25 USD, 7",
"38 GBP, 2",
"null,   0"
})
public void testMethod(Money money, int anotherParameter) {
...
}

If you don't want or can't use custom runner (eg. you are already using an other runner, like Robolectric runner), you can try this DataSet Rule.

A much better way (allows you to have more than one test method) is to use JUnit with JUnitParams:

import junitparams.Parameters;
import org.junit.Test;


@RunWith(JUnitParamsRunner.class)
Public class TestClass() {


@Test
@Parameters(method = "generateTestData")
public void test1(int value, String text, MyObject myObject) {
... Test Code ...
}


.... Other @Test methods ....


Object[] generateTestData() {
MyObject objectA1 = new MyObject();
MyObject objectA2 = new MyObject();
MyObject objectA3 = new MyObject();


return $(
$(400, "First test text.", objectA1),
$(402, "Second test text.", objectA2),
$(403, "Third test text.", objectA3)
);
}
}

You can get the junitparams project here.

If you are already using a @RunWith in your test class you probably need to take a look at this.

In JUnit 5 you could use @ParameterizedTest and @ValueSource to get a method called multiple times with different input values.

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;


public class PrimeTest {
@ParameterizedTest
@ValueSource(ints = {1, 2, 3, 4, 5})
public void isPrime(int candidate) {
// called with candidate=1, candidate=2, etc.
}
}