Search code examples
javajunit

How to make a JUnit test that does the same test on many values in a list?


I have a JUnit test with one @Test method that does the same test on a long list of values.

When I run the "tests" there's just one green check mark JUnit test success (in the Eclipse UI).

How can I tweak this so each value test appears as a separate JUnit test in the UI so I can more easily locate which one fails?

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MyBigTest {

@Test
public void testAllValues() {
   List<String> allValues = new ArrayList<String>();
   allValues.add("value1");
   allValues.add("value2");
   allValues.add("value3");
   allValues.add("value4");
   allValues.add("value5");

   for (String value : allValues) {
      String something1 = doSomethingToValue(value1);
      if (something1 == BAD) {
         throw Exception("bad "+value);
      }
   }
}
  

Solution

  • It seems that you are still using JUnit 4 (because you annotated your class with @RunWith().)

    With JUnit 4 writing parameterized tests for Spring applications is fairly complex because you can have only one TestRunner and for parameterized tests you need to use the Parameterized runner. And that means that setting up the Spring application cannot be done automatically by using the SpringRunner.

    https://www.baeldung.com/springjunit4classrunner-parameterized has a detailed example how you can achieve this.


    The whole thing would be a lot easier if you could switch your test to JUnit 5 because JUnit 5 has better support for parameterized tests:

    import org.junit.jupiter.api.Test;
    
    @SpringBootTest(classes = Application.class)
    public class MyBigTest {
    
    @ParameterizedTest
    @ValueSource(strings = {"value1", "value2", "value3", "value4", "value5"})
    public void testAllValues(String value) {
    
        String something1 = doSomethingToValue(value);
        if (something1 == BAD) {
            throw Exception("bad "+value);
        }
    }
    

    Note that you don't need to migrate all your tests to JUnit 5 - JUnit 5 can also run JUnit 4 tests.