Running the same JUnit test case multiple time with different data

Viewed 74424

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?

9 Answers

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};
}

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.

Related