Pass null values in JUnit 5 @CsvSource

Pass null values in JUnit 5 @CsvSource

JUnit 5 @CsvSource allows writing parameterized tests without creating a CSV file or writing a method to feed data. However, handling nulls is not provided out of the box and requires a bit of configuration. In this article, we cover how to pass null values in JUnit 5 @CsvSource annotation.

Let’s start by writing a simple test that verifies the Apache StringUtils.isBlank() functionality. The isBlank method returns true if the given string is null, or white space.

We can test the method as follows,

@ParameterizedTest
@CsvSource(value = {
    "'', true", // case 0
    "'     ', true", // case 1
    "null, true", // case 2
    "abc, false" // case 3
})
void shouldReturnNullOnNullOrWhitespace(String input, boolean expected) {
    assertEquals(expected, StringUtils.isBlank(input));
}

If we run the test, it will fail on case two as Java does not evaluate the "null" string as null. To tackle the issue, we need to modify our test and add nullValues in the annotation as follows,

@ParameterizedTest
@CsvSource(value = {
    "'', true", // case 0
    "'     ', true", // case 1
    "null, true", // case 2
    "abc, false" // case 3
}, nullValues = "null")
void shouldReturnNullOnNullOrWhitespace(String input, boolean expected) {
    assertEquals(expected, StringUtils.isBlank(input));
}

Adding the nullValues specifies the string, "null" in the above example, should be interpreted as null.

Additionally, we can assign more than one value to nullValues and instruct JUnit to convert those values to null.

@ParameterizedTest
@CsvSource(value = {
    "'', true", // case 0
    "'     ', true", // case 1
    "null, true", // case 2
    "nil, true", // case 3
    "NULL, true", // case 4
    "abc, false" // case 5
}, nullValues = {"null", "nil", "NULL"})
void shouldReturnNullOnNullOrWhitespace(String input, boolean expected) {
    assertEquals(expected, StringUtils.isBlank(input));
}

In the above test values null, nil, and NULL would be converted to null.

Conclusion

In this article, we discuss how to pass null values to JUnit 5 @CsvSource annotation using the nullValues annotation attribute. For more Java tips, check our Java tutorials.

Inline/featured images credits