How to pass multiple parameters to @ValueSource
Asked Answered
B

4

8

I'm trying to perform a parametrized JUnit 5 test, how to accomplish the following?

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

I know I could use @MethodSource but I was wondering if in my case I just need to understand better @ValueSource.

Beatify answered 16/6, 2020 at 7:11 Comment(0)
G
8

The documentation says:

@ValueSource is one of the simplest possible sources. It lets you specify a single array of literal values and can only be used for providing a single argument per parameterized test invocation.

Indeed you need to use @MethodSource for multiple arguments, or implement the ArgumentsProvider interface.

Gissing answered 24/6, 2020 at 16:27 Comment(0)
U
7

Another approach is to use @CsvSource, which is a bit of a hack, but can autocast stringified values to primitives. If you need array data, then you can implement your own separator and manually split inside the function.

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);
}
Urethroscope answered 19/2, 2021 at 2:13 Comment(2)
For my simple use-case where I had to pass 2 integers that worked greatScrapbook
I added an answer with a variation of this which can handle arbitrary argumentsVengeance
U
6

You need jUnit Pioneer and the @CartesianProductTest

POM:

<dependency>
    <groupId>org.junit-pioneer</groupId>
    <artifactId>junit-pioneer</artifactId>
    <version>1.3.0</version>
    <scope>test</scope>
</dependency>

Java:

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
}
Urethroscope answered 19/2, 2021 at 1:28 Comment(0)
V
1

You can also use @CsvSource with arbitrary amount of arguments:

@ParameterizedTest
@CsvSource({
        "1, a",
        "2, a,b",
        "3, a,b,c"
})
void castTermVectorsResponse(ArgumentsAccessor argumentsAccessor) {
    int size = argumentsAccessor.getInteger(0);
    List<String> list = argumentsAccessor.toList().stream().skip(1).map(String::valueOf).toList();
    assertThat(size).isEqualTo(list.size());
}
Vengeance answered 5/7, 2023 at 6:57 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.