Anleitung zu JUnit 5 Parametrisierten Tests

1. Übersicht

JUnit 5, die nächste Generation von JUnit, erleichtert das Schreiben von Entwicklertests mit neuen und glänzenden Funktionen.

Eine solche Funktion ist p arameterized Tests. Mit dieser Funktion können wir eine einzelne Testmethode mehrmals mit unterschiedlichen Parametern ausführen.

In diesem Tutorial werden wir uns eingehend mit parametrisierten Tests befassen. Beginnen wir also!

2. Abhängigkeiten

Um JUnit 5-parametrisierte Tests verwenden zu können, müssen wir das Artefakt junit-jupiter-params von JUnit Platform importieren . Das heißt, wenn wir Maven verwenden, fügen wir unserer pom.xml Folgendes hinzu :

 org.junit.jupiter junit-jupiter-params 5.7.0 test 

Wenn Sie Gradle verwenden, geben wir es auch etwas anders an:

testCompile("org.junit.jupiter:junit-jupiter-params:5.7.0")

3. Erster Eindruck

Nehmen wir an, wir haben eine vorhandene Dienstprogrammfunktion und möchten uns über deren Verhalten sicher sein:

public class Numbers { public static boolean isOdd(int number) { return number % 2 != 0; } }

Parametrisierte Tests sind wie andere Tests, außer dass wir die Annotation @ParameterizedTest hinzufügen :

@ParameterizedTest @ValueSource(ints = {1, 3, 5, -3, 15, Integer.MAX_VALUE}) // six numbers void isOdd_ShouldReturnTrueForOddNumbers(int number) { assertTrue(Numbers.isOdd(number)); }

JUnit 5-Testläufer führt diesen obigen Test - und folglich die isOdd- Methode - sechsmal aus. Und jedes Mal weist es dem Parameter number method einen anderen Wert als das Array @ValueSource zu .

Dieses Beispiel zeigt uns also zwei Dinge, die wir für einen parametrisierten Test benötigen:

  • In diesem Fall eine Argumentquelle , ein int- Array
  • eine Möglichkeit, auf sie zuzugreifen , in diesem Fall den Parameter number

Es gibt noch eine weitere Sache, die in diesem Beispiel nicht ersichtlich ist. Bleiben Sie also auf dem Laufenden.

4. Argumentquellen

Wie wir inzwischen wissen sollten, führt ein parametrisierter Test denselben Test mehrmals mit unterschiedlichen Argumenten aus.

Und hoffentlich können wir mehr als nur Zahlen - also lasst uns erkunden!

4.1. Einfache Werte

Mit der Annotation @ValueSource können wir ein Array von Literalwerten an die Testmethode übergeben .

Angenommen, wir testen unsere einfache isBlank- Methode:

public class Strings { public static boolean isBlank(String input)  return input == null  }

Wir erwarten von dieser Methode, dass sie für leere Zeichenfolgen true für null zurückgibt. Wir können also einen parametrisierten Test wie den folgenden schreiben, um dieses Verhalten zu bestätigen:

@ParameterizedTest @ValueSource(strings = {"", " "}) void isBlank_ShouldReturnTrueForNullOrBlankStrings(String input) { assertTrue(Strings.isBlank(input)); } 

Wie wir sehen können, führt JUnit diesen Test zweimal aus und weist dem Methodenparameter jedes Mal ein Argument aus dem Array zu.

Eine der Einschränkungen von Wertquellen besteht darin, dass sie nur die folgenden Typen unterstützen:

  • kurz (mit dem Attribut shorts )
  • Byte (mit dem Attribut bytes )
  • int (mit dem Attribut ints )
  • long (mit dem Attribut longs )
  • schweben (mit dem Schwimmer Attribute)
  • Doppel (mit Doppel - Attribute)
  • char (mit dem chars- Attribut)
  • java.lang.String (mit dem Zeichenfolgenattribut )
  • java.lang.Class (mit dem Klassenattribut )

Außerdem können wir jedes Mal nur ein Argument an die Testmethode übergeben .

Und bevor wir weiter gingen, hat jemand bemerkt, dass wir als Argument nicht null übergeben haben ? Das ist eine weitere Einschränkung: Wir können eine @ValueSource nicht null übergeben, selbst für String und Klasse !

4.2. Null- und leere Werte

Ab JUnit 5.4 können wir mit @NullSource einen einzelnen Nullwert an eine parametrisierte Testmethode übergeben:

@ParameterizedTest @NullSource void isBlank_ShouldReturnTrueForNullInputs(String input) { assertTrue(Strings.isBlank(input)); }

Da primitive Datentypen keine Nullwerte akzeptieren können, können wir die @NullSource nicht für primitive Argumente verwenden.

Ganz ähnlich können wir leere Werte mit der Annotation @EmptySource übergeben :

@ParameterizedTest @EmptySource void isBlank_ShouldReturnTrueForEmptyStrings(String input) { assertTrue(Strings.isBlank(input)); }

@EmptySource übergibt ein einzelnes leeres Argument an die mit Anmerkungen versehene Methode .

Bei String- Argumenten wäre der übergebene Wert so einfach wie ein leerer String . Darüber hinaus kann diese Parameterquelle leere Werte für Sammlungstypen und Arrays bereitstellen .

Um sowohl Null- als auch Leerwerte zu übergeben , können wir die zusammengesetzte Annotation @NullAndEmptySource verwenden :

@ParameterizedTest @NullAndEmptySource void isBlank_ShouldReturnTrueForNullAndEmptyStrings(String input) { assertTrue(Strings.isBlank(input)); }

Wie bei der @EmptySource arbeitet die zusammengesetzte Anmerkung für String s , Sammlung s , und Arrays .

In order to pass a few more empty string variations to the parameterized test, we can combine @ValueSource, @NullSource, and @EmptySource together:

@ParameterizedTest @NullAndEmptySource @ValueSource(strings = {" ", "\t", "\n"}) void isBlank_ShouldReturnTrueForAllTypesOfBlankStrings(String input) { assertTrue(Strings.isBlank(input)); }

4.3. Enum

In order to run a test with different values from an enumeration, we can use the @EnumSource annotation.

For example, we can assert that all month numbers are between 1 and 12:

@ParameterizedTest @EnumSource(Month.class) // passing all 12 months void getValueForAMonth_IsAlwaysBetweenOneAndTwelve(Month month) { int monthNumber = month.getValue(); assertTrue(monthNumber >= 1 && monthNumber <= 12); }

Or, we can filter out a few months by using the names attribute.

How about asserting the fact that April, September, June, and November are 30 days long:

@ParameterizedTest @EnumSource(value = Month.class, names = {"APRIL", "JUNE", "SEPTEMBER", "NOVEMBER"}) void someMonths_Are30DaysLong(Month month) { final boolean isALeapYear = false; assertEquals(30, month.length(isALeapYear)); }

By default, the names will only keep the matched enum values. We can turn this around by setting the mode attribute to EXCLUDE:

@ParameterizedTest @EnumSource( value = Month.class, names = {"APRIL", "JUNE", "SEPTEMBER", "NOVEMBER", "FEBRUARY"}, mode = EnumSource.Mode.EXCLUDE) void exceptFourMonths_OthersAre31DaysLong(Month month) { final boolean isALeapYear = false; assertEquals(31, month.length(isALeapYear)); }

In addition to literal strings, we can pass a regular expression to the names attribute:

@ParameterizedTest @EnumSource(value = Month.class, names = ".+BER", mode = EnumSource.Mode.MATCH_ANY) void fourMonths_AreEndingWithBer(Month month) { EnumSet months = EnumSet.of(Month.SEPTEMBER, Month.OCTOBER, Month.NOVEMBER, Month.DECEMBER); assertTrue(months.contains(month)); }

Quite similar to @ValueSource, @EnumSource is only applicable when we're going to pass just one argument per test execution.

4.4. CSV Literals

Suppose we're going to make sure that the toUpperCase() method from String generates the expected uppercase value. @ValueSource won't be enough.

In order to write a parameterized test for such scenarios, we have to:

  • Pass an input value and an expected value to the test method
  • Compute the actual result with those input values
  • Assert the actual value with the expected value

So, we need argument sources capable of passing multiple arguments. The @CsvSource is one of those sources:

@ParameterizedTest @CsvSource({"test,TEST", "tEst,TEST", "Java,JAVA"}) void toUpperCase_ShouldGenerateTheExpectedUppercaseValue(String input, String expected) { String actualValue = input.toUpperCase(); assertEquals(expected, actualValue); }

The @CsvSource accepts an array of comma-separated values and each array entry corresponds to a line in a CSV file.

This source takes one array entry each time, splits it by comma and passes each array to the annotated test method as separate parameters. By default, the comma is the column separator but we can customize it using the delimiter attribute:

@ParameterizedTest @CsvSource(value = {"test:test", "tEst:test", "Java:java"}, delimiter = ':') void toLowerCase_ShouldGenerateTheExpectedLowercaseValue(String input, String expected) { String actualValue = input.toLowerCase(); assertEquals(expected, actualValue); }

Now it's a colon-separated value, still a CSV!

4.5. CSV Files

Instead of passing the CSV values inside the code, we can refer to an actual CSV file.

For example, we could use a CSV file like:

input,expected test,TEST tEst,TEST Java,JAVA

We can load the CSV file and ignore the header column with @CsvFileSource:

@ParameterizedTest @CsvFileSource(resources = "/data.csv", numLinesToSkip = 1) void toUpperCase_ShouldGenerateTheExpectedUppercaseValueCSVFile( String input, String expected) { String actualValue = input.toUpperCase(); assertEquals(expected, actualValue); }

The resources attribute represents the CSV file resources on the classpath to read. And, we can pass multiple files to it.

The numLinesToSkip attribute represents the number of lines to skip when reading the CSV files. By default, @CsvFileSource does not skip any lines, but this feature is usually useful for skipping the header lines, like we did here.

Just like the simple @CsvSource, the delimiter is customizable with the delimiter attribute.

In addition to the column separator:

  • The line separator can be customized using the lineSeparator attribute – a newline is the default value
  • The file encoding is customizable using the encoding attribute – UTF-8 is the default value

4.6. Method

The argument sources we've covered so far are somewhat simple and share one limitation: It's hard or impossible to pass complex objects using them!

One approach to providing more complex arguments is to use a method as an argument source.

Let's test the isBlank method with a @MethodSource:

@ParameterizedTest @MethodSource("provideStringsForIsBlank") void isBlank_ShouldReturnTrueForNullOrBlankStrings(String input, boolean expected) { assertEquals(expected, Strings.isBlank(input)); }

The name we supply to @MethodSource needs to match an existing method.

So let's next write provideStringsForIsBlank, a static method that returns a Stream of Arguments:

private static Stream provideStringsForIsBlank() { return Stream.of( Arguments.of(null, true), Arguments.of("", true), Arguments.of(" ", true), Arguments.of("not blank", false) ); }

Here we're literally returning a stream of arguments, but it's not a strict requirement. For example, we can return any other collection-like interfaces like List.

If we're going to provide just one argument per test invocation, then it's not necessary to use the Arguments abstraction:

@ParameterizedTest @MethodSource // hmm, no method name ... void isBlank_ShouldReturnTrueForNullOrBlankStringsOneArgument(String input) { assertTrue(Strings.isBlank(input)); } private static Stream isBlank_ShouldReturnTrueForNullOrBlankStringsOneArgument() { return Stream.of(null, "", " "); }

When we don't provide a name for the @MethodSource, JUnit will search for a source method with the same name as the test method.

Sometimes it's useful to share arguments between different test classes. In these cases, we can refer to a source method outside of the current class by its fully-qualified name:

class StringsUnitTest { @ParameterizedTest @MethodSource("com.baeldung.parameterized.StringParams#blankStrings") void isBlank_ShouldReturnTrueForNullOrBlankStringsExternalSource(String input) { assertTrue(Strings.isBlank(input)); } } public class StringParams { static Stream blankStrings() { return Stream.of(null, "", " "); } }

Using the FQN#methodName format we can refer to an external static method.

4.7. Custom Argument Provider

Another advanced approach to pass test arguments is to use a custom implementation of an interface called ArgumentsProvider:

class BlankStringsArgumentsProvider implements ArgumentsProvider { @Override public Stream provideArguments(ExtensionContext context) { return Stream.of( Arguments.of((String) null), Arguments.of(""), Arguments.of(" ") ); } }

Then we can annotate our test with the @ArgumentsSource annotation to use this custom provider:

@ParameterizedTest @ArgumentsSource(BlankStringsArgumentsProvider.class) void isBlank_ShouldReturnTrueForNullOrBlankStringsArgProvider(String input) { assertTrue(Strings.isBlank(input)); }

Let's make the custom provider a more pleasant API to use with a custom annotation!

4.8. Custom Annotation

How about loading the test arguments from a static variable? Something like:

static Stream arguments = Stream.of( Arguments.of(null, true), // null strings should be considered blank Arguments.of("", true), Arguments.of(" ", true), Arguments.of("not blank", false) ); @ParameterizedTest @VariableSource("arguments") void isBlank_ShouldReturnTrueForNullOrBlankStringsVariableSource( String input, boolean expected) { assertEquals(expected, Strings.isBlank(input)); }

Actually, JUnit 5 does not provide this! However, we can roll our own solution.

First off, we can create an annotation:

@Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @ArgumentsSource(VariableArgumentsProvider.class) public @interface VariableSource { /** * The name of the static variable */ String value(); }

Then we need to somehow consume the annotation details and provide test arguments. JUnit 5 provides two abstractions to achieve those two things:

  • AnnotationConsumer to consume the annotation details
  • ArgumentsProvider to provide test arguments

So, we next need to make the VariableArgumentsProvider class read from the specified static variable and return its value as test arguments:

class VariableArgumentsProvider implements ArgumentsProvider, AnnotationConsumer { private String variableName; @Override public Stream provideArguments(ExtensionContext context) { return context.getTestClass() .map(this::getField) .map(this::getValue) .orElseThrow(() -> new IllegalArgumentException("Failed to load test arguments")); } @Override public void accept(VariableSource variableSource) { variableName = variableSource.value(); } private Field getField(Class clazz) { try { return clazz.getDeclaredField(variableName); } catch (Exception e) { return null; } } @SuppressWarnings("unchecked") private Stream getValue(Field field) { Object value = null; try { value = field.get(null); } catch (Exception ignored) {} return value == null ? null : (Stream) value; } }

And it works like a charm!

5. Argument Conversion

5.1. Implicit Conversion

Let's re-write one of those @EnumTests with a @CsvSource:

@ParameterizedTest @CsvSource({"APRIL", "JUNE", "SEPTEMBER", "NOVEMBER"}) // Pssing strings void someMonths_Are30DaysLongCsv(Month month) { final boolean isALeapYear = false; assertEquals(30, month.length(isALeapYear)); }

This shouldn't work, right? But, somehow it does!

So, JUnit 5 converts the String arguments to the specified enum type. To support use cases like this, JUnit Jupiter provides a number of built-in implicit type converters.

The conversion process depends on the declared type of each method parameter. The implicit conversion can convert the String instances to types like:

  • UUID
  • Locale
  • LocalDate, LocalTime, LocalDateTime, Year, Month, etc.
  • File and Path
  • URL and URI
  • Enum subclasses

5.2. Explicit Conversion

Sometimes we need to provide a custom and explicit converter for arguments.

Suppose we want to convert strings with the yyyy/mm/ddformat to LocalDate instances. First off, we need to implement the ArgumentConverter interface:

class SlashyDateConverter implements ArgumentConverter { @Override public Object convert(Object source, ParameterContext context) throws ArgumentConversionException { if (!(source instanceof String)) { throw new IllegalArgumentException( "The argument should be a string: " + source); } try { String[] parts = ((String) source).split("/"); int year = Integer.parseInt(parts[0]); int month = Integer.parseInt(parts[1]); int day = Integer.parseInt(parts[2]); return LocalDate.of(year, month, day); } catch (Exception e) { throw new IllegalArgumentException("Failed to convert", e); } } }

Then we should refer to the converter via the @ConvertWith annotation:

@ParameterizedTest @CsvSource({"2018/12/25,2018", "2019/02/11,2019"}) void getYear_ShouldWorkAsExpected( @ConvertWith(SlashyDateConverter.class) LocalDate date, int expected) { assertEquals(expected, date.getYear()); }

6. Argument Accessor

By default, each argument provided to a parameterized test corresponds to a single method parameter. Consequently, when passing a handful of arguments via an argument source, the test method signature gets very large and messy.

One approach to address this issue is to encapsulate all passed arguments into an instance of ArgumentsAccessor and retrieve arguments by index and type.

For example, let's consider our Person class:

class Person { String firstName; String middleName; String lastName; // constructor public String fullName() { if (middleName == null || middleName.trim().isEmpty()) { return String.format("%s %s", firstName, lastName); } return String.format("%s %s %s", firstName, middleName, lastName); } }

Then, in order to test the fullName() method, we'll pass four arguments: firstName, middleName, lastName, and the expected fullName. We can use the ArgumentsAccessor to retrieve the test arguments instead of declaring them as method parameters:

@ParameterizedTest @CsvSource({"Isaac,,Newton,Isaac Newton", "Charles,Robert,Darwin,Charles Robert Darwin"}) void fullName_ShouldGenerateTheExpectedFullName(ArgumentsAccessor argumentsAccessor) { String firstName = argumentsAccessor.getString(0); String middleName = (String) argumentsAccessor.get(1); String lastName = argumentsAccessor.get(2, String.class); String expectedFullName = argumentsAccessor.getString(3); Person person = new Person(firstName, middleName, lastName); assertEquals(expectedFullName, person.fullName()); }

Here, we're encapsulating all passed arguments into an ArgumentsAccessor instance and then, in the test method body, retrieving each passed argument with its index. In addition to just being an accessor, type conversion is supported through get* methods:

  • getString(index) retrieves an element at a specific index and converts it to Stringthe same is true for primitive types
  • get(index) simply retrieves an element at a specific index as an Object
  • get(index, type) retrieves an element at a specific index and converts it to the given type

7. Argument Aggregator

Using the ArgumentsAccessor abstraction directly may make the test code less readable or reusable. In order to address these issues, we can write a custom and reusable aggregator.

To do that, we implement the ArgumentsAggregator interface:

class PersonAggregator implements ArgumentsAggregator { @Override public Object aggregateArguments(ArgumentsAccessor accessor, ParameterContext context) throws ArgumentsAggregationException { return new Person( accessor.getString(1), accessor.getString(2), accessor.getString(3)); } }

And then we reference it via the @AggregateWith annotation:

@ParameterizedTest @CsvSource({"Isaac Newton,Isaac,,Newton", "Charles Robert Darwin,Charles,Robert,Darwin"}) void fullName_ShouldGenerateTheExpectedFullName( String expectedFullName, @AggregateWith(PersonAggregator.class) Person person) { assertEquals(expectedFullName, person.fullName()); }

The PersonAggregator takes the last three arguments and instantiates a Person class out of them.

8. Customizing Display Names

By default, the display name for a parameterized test contains an invocation index along with a String representation of all passed arguments, something like:

├─ someMonths_Are30DaysLongCsv(Month) │ │ ├─ [1] APRIL │ │ ├─ [2] JUNE │ │ ├─ [3] SEPTEMBER │ │ └─ [4] NOVEMBER

However, we can customize this display via the name attribute of the @ParameterizedTest annotation:

@ParameterizedTest(name = "{index} {0} is 30 days long") @EnumSource(value = Month.class, names = {"APRIL", "JUNE", "SEPTEMBER", "NOVEMBER"}) void someMonths_Are30DaysLong(Month month) { final boolean isALeapYear = false; assertEquals(30, month.length(isALeapYear)); }

April is 30 days long surely is a more readable display name:

├─ someMonths_Are30DaysLong(Month) │ │ ├─ 1 APRIL is 30 days long │ │ ├─ 2 JUNE is 30 days long │ │ ├─ 3 SEPTEMBER is 30 days long │ │ └─ 4 NOVEMBER is 30 days long

The following placeholders are available when customizing the display name:

  • {index} will be replaced with the invocation index – simply put, the invocation index for the first execution is 1, for the second is 2, and so on
  • {arguments} is a placeholder for the complete, comma-separated list of arguments
  • {0}, {1}, ... are placeholders for individual arguments

9. Conclusion

In this article, we've explored the nuts and bolts of parameterized tests in JUnit 5.

We learned that parameterized tests are different from normal tests in two aspects: they're annotated with the @ParameterizedTest, and they need a source for their declared arguments.

Also, by now, we should now that JUnit provides some facilities to convert the arguments to custom target types or to customize the test names.

Wie üblich sind die Beispielcodes in unserem GitHub-Projekt verfügbar. Schauen Sie sich das also unbedingt an!