首页 > 解决方案 > Junit 5 - 如何为@CsvSource 传递多个空值?

问题描述

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

@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();
}

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

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

我找不到解决方法,而且我看到的解决方案相当笨拙和麻烦。有没有更简单的方法来提供价值null

标签: junitjunit5

解决方案


@CsvSource有一个名为 的属性nullValues。请参阅文档

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

@CsvSource(value= {"null, null",
                   "foo, bar"}
           , nullValues={"null"})

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

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

@CsvSource({",",
            "foo, bar"})

推荐阅读