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?
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?
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};
}
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:
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.
}
}
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.