How to use JUnit5 Parametrized Test CSV file source?

10.2k views Asked by At

I am trying to run a parametrized test from CSV-file.

It is working if I use just CSVSource like that:

@ParameterizedTest
@CsvSource({ "a,A", "b,B" })
void csvSourceTest(String input, String expected) {
    String actualValue = input.toUpperCase();
    assertEquals(expected, actualValue);
}

But if I try the same thing from a file it won't work:

@ParameterizedTest
@CsvFileSource(resources = "/data.csv")
void csvFileSourceTest(String input, String expected) {
    String actualValue = input.toUpperCase();
    assertEquals(expected, actualValue);
}

I have also tried using a hard path to my file but for the file test in Eclipse I always get the message

No tests found with test runnter 'JUnit 5'.

Where does JUnit expect the file?

These are my dependencies:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <version>5.1.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.1.0</version>
    <scope>test</scope>
</dependency>

Does anybody know what I might be missing or where the error is?

Thanks in advance
PAUL

2

There are 2 answers

0
kidney On BEST ANSWER

The JUnit5 user guide states that the CSV file needs to be on the classpath. In case of a Maven project that would be src/test/resources.

0
27P On

In Kotlin

CSV file is placed here:

/src/test/resources/post_data.csv

Test read csv test data:

        @ParameterizedTest(name = "{index} => post with {0} : {1} : {2}")
        @CsvFileSource(resources = ["/post_data.csv"],)
        fun testPostWithValidData(id: String?, text: String?, completed: String?) {
          //test body
          ......

        }

Gradle dependencies:

// JUnit5 testImplementation("org.junit.jupiter:junit-jupiter-api:$junitVersion") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:$junitVersion") testImplementation("org.junit.jupiter:junit-jupiter-params:$junitVersion") testRuntimeOnly("org.junit.jupiter:junit-jupiter-params:$junitVersion")