5.1 @ParameterizedTest annotation

Sometimes you just want to call the test multiple times with different parameters: different values, different input parameters, different usernames. JUnit aims to make your life easier, so for this case it has such a thing as parameterized tests.

To use parameterized tests, you need to add one more dependency to your pom.xml:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <version>5.8.2</version>
    <scope>test</scope>
</dependency>

Then we can consider an example:

@ParameterizedTest
@ValueSource(ints = { 1, 2, 3 })
void testMethod(int argument) {
    //test code
}

@ParameterizedTest
@ValueSource(ints = { 1, 2, 3 })
void testMethodWithAutoboxing(Integer argument) {
    //test code
}

Each test method will be called 3 times, and each time it is called, another parameter will be passed to it. Values ​​are set using another annotation - @ValueSource . But more needs to be said about it.

5.2 @ValueSource annotation

The @ValueSource annotation is great for working with primitives and literals. Just list the parameter values ​​separated by commas and the test will be called once for each value.

@ParameterizedTest
@ValueSource(ints = { 1, 2, 3 })
void testMethodWithAutoboxing(Integer argument) {
    //test code
}

But there is also a minus - this annotation does not support null, so you will need to use a special crutch for it - @NullSource . It looks like this:

@ParameterizedTest
@NullSource
void testMethodNullSource(Integer argument) {
    assertTrue(argument == null);
}

5.3 @EnumSource annotation

There is also a special annotation @EnumSource , which passes all the values ​​of a specific Enum to the method. Its application looks like this:

enum Direction {
    EAST, WEST, NORTH, SOUTH
}

@ParameterizedTest
@EnumSource(Direction.class)
void testWithEnumSource(Direction d) {
    assertNotNull(d);
}

5.4 @MethodSource annotation

But how to pass objects as parameters? Especially if they have a complex construction algorithm. To do this, you can simply specify a special helper method that will return a list (Stream) of such values.

Example:

@ParameterizedTest
@MethodSource("argsProviderFactory")
void testWithMethodSource(String argument) {
    assertNotNull(argument);
}

static Stream<String> argsProviderFactory() {
    return Stream.of("one", "two",  "three");
}

Parameterized Tests with Multiple Arguments

Of course, you have already wondered what to do if you want to pass several parameters to the method. There is a very cool @CSVSource annotation for this . It allows you to list the values ​​of the method parameters simply separated by commas.

Example:

@ParameterizedTest
@CsvSource({
    "alex, 30, Programmer, Working",
    "brian, 35, Tester, Working",
	"charles, 40, manager, kicks"
})
void testWithCsvSource(String name, int age, String occupation, String status) {
	//method code
}