Published on

Using JUnit 5's Parameterized Tests and @MethodSource

Authors

One issue I often find is that the test data used in a test can often bloat the test making it difficult to follow what is going on in the class. The way I normally deal with this is move the test data portion of the test class to a Helper class and then use that in my tests. JUnit 5 allows you to use what is called a Parameterized test where the same test can be run multiple times using different arguments. This is ideally suited for wiring in test data that you produce in a method, list, class or enum.

For my use case I used the @MethodSource annotation to point a test to a method that would supply my data. In this method I call the test data provider class:

@ParameterizedTest
@MethodSource("myDataProviderMethod")
void myTestWithComplexDataSetup(MyComplexTestData wiredData){
   ...
   //tests using wiredData
   ...
}

static Stream<MyComplexTestData> myDataProviderMethod(){
     return Stream.of(new MyComplexDataProvider().build());
}

In my case I only needed one piece of data to be provided hence I make the data provider method return a Stream. If I wanted to return multiple items I would have instead returned something that implements Iterable or Iterator like a List or Set. It is also important to note that the data provider method has to be static.