如何将多个参数传递给@ValueSource

Pha*_*ate 7 junit5 spring-boot-test

我正在尝试执行参数化 JUnit 5 测试,如何完成以下任务?

@ParametrizedTest
@ValueSource //here it seems only one parameter is supported
public void myTest(String parameter, String expectedOutput)
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用@MethodSource,但我想知道在我的情况下我是否只需要更好地理解@ValueSource

小智 8

文档说:

@ValueSource 是最简单的来源之一。它允许您指定单个文字值数组,并且只能用于为每个参数化测试调用提供单个参数

事实上,您需要使用@MethodSource多个参数,或实现ArgumentsProvider接口。


Jam*_*gan 7

另一种方法是使用@CsvSource,这有点麻烦,但可以将字符串化值自动转换为基元。如果您需要数组数据,那么您可以实现自己的分隔符并在函数内手动拆分。

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static com.google.common.truth.Truth.assertThat;

@ParameterizedTest
@CsvSource({
    "1, a",
    "2, a;b",
    "3, a;b;c"
})
void castTermVectorsResponse(Integer size, String encodedList) {
    String[] list = encodedList.split(";");
    assertThat(size).isEqualTo(list.length);
}
Run Code Online (Sandbox Code Playgroud)


Jam*_*gan 5

您需要 jUnit Pioneer 和@CartesianProductTest

聚甲醛:

<dependency>
    <groupId>org.junit-pioneer</groupId>
    <artifactId>junit-pioneer</artifactId>
    <version>1.3.0</version>
    <scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

爪哇:

import org.junitpioneer.jupiter.CartesianProductTest;
import org.junitpioneer.jupiter.CartesianValueSource;

@CartesianProductTest
@CartesianValueSource(ints = { 1, 2 })
@CartesianValueSource(ints = { 3, 4 })
void myCartesianTestMethod(int x, int y) {
    // passing test code
}
Run Code Online (Sandbox Code Playgroud)