Junit 5 - 如何为@CsvSource 传递多个空值?

夢のの*_*のの夢 7 junit junit5

我正在将测试方法从单个参数修改为多个:

@ParameterizedTest
@NullSource
@ValueSource({"foo", "bar"..})
void shouldReturnFalse(String x) {
  assertThat(someMethod(x)).isFalse();
}

@ParameterizedTest
@CsvSource({
  "null, null",
  "foo, bar"
})
void shouldReturnFalse(String x, String y) {
  assertThat(someMethod(x, y)).isFalse();
}
Run Code Online (Sandbox Code Playgroud)

null这里作为字符串文字而不是空文字传入。结果,此测试失败。此测试以前使用单个参数 with @NullSource,但在切换到多个参数时会出现以下错误:

org.junit.jupiter.api.extension.ParameterResolutionException:没有为参数注册 ParameterResolver...

我找不到解决这个问题的方法,我看到的解决方案相当笨拙和繁琐。有没有更简单的方法来提供值null

Jan*_*itz 14

@CsvSource有一个名为nullValues. 请参阅文档

应解释为空引用的字符串列表。

@CsvSource(value= {"null, null",
                   "foo, bar"}
           , nullValues={"null"})
Run Code Online (Sandbox Code Playgroud)

另一种选择是简单地不传递先前链接的文档中所述的任何值。

请注意,无论此 nullValues 属性的值如何,未加引号的空值将始终转换为空引用;而带引号的空字符串将被视为 emptyValue()。

@CsvSource({",",
            "foo, bar"})
Run Code Online (Sandbox Code Playgroud)


小智 11

您可以按照 @Jan Schmitz 上面的解释使用 nullValues,或者您可以像这样丢弃 null 值:

@CsvSource({
  ",",
  "foo, bar"
})
Run Code Online (Sandbox Code Playgroud)