docs
docs copied to clipboard
Recipe: parametrized tests in JUnit 5
trafficstars
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.*;
import org.junit.jupiter.params.provider.*;
import static org.junit.jupiter.api.Assertions.*;
// Values source
@ParameterizedTest
@ValueSource(strings = {"", " "})
void isBlank_ShouldReturnTrueForNullOrBlankStrings(String input) {
assertTrue(Strings.isBlank(input));
}
// CSV source
@ParameterizedTest
@CsvSource({"test,TEST", "tEst,TEST", "Java,JAVA"})
void toUpperCase_ShouldGenerateTheExpectedUppercaseValue(String input, String expected) {
String actualValue = input.toUpperCase();
assertEquals(expected, actualValue);
}
// Generator method
@ParameterizedTest
@MethodSource("provideStringsForIsBlank")
void isBlank_ShouldReturnTrueForNullOrBlankStrings(String input, boolean expected) {
assertEquals(expected, Strings.isBlank(input));
}
private static Stream<Arguments> provideStringsForIsBlank() {
return Stream.of(
Arguments.of(null, true),
Arguments.of("", true),
Arguments.of(" ", true),
Arguments.of("not blank", false)
);
}
I would suggest to add also display names:
import org.junit.jupiter.api.DisplayName;
@DisplayName("Tests with JUnit 5")
class SampleTests {
@ParameterizedTest(name = "input: '{0}' and I expect you to return >>{1}<<")
@DisplayName("We test some fixed Strings")
@CsvSource({"test,TEST", "tEst,TEST"})
void toUpperCase_ShouldGenerateTheExpectedUppercaseValue(String input, String expected) {
String actualValue = input.toUpperCase();
assertEquals(expected, actualValue);
}
}
This will lead to the following output:

Finally readable parametrized tests in java...? XD
What about the order of the test methods?
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SampleTests {
@Test
@Order(2)
void secondTest() { ... }
@Test
@Order(1)
void firstTest() { ... }
}
Other built-in possibilities are
- ~~
MethodOrderer.Alphanumeric~~ (deprecated since JUnit 5.7, but will only be removed in JUnit 6) MethodOrderer.DisplayName(since 5.7, still experimental in latest 5.8.2)MethodOrderer.MethodName(since 5.7, still experimental in latest 5.8.2)MethodOrderer.Random
CW currently uses JUnit 5.4.0