Introduction
In this post, we will cover how to use CSV string or file as a source of parameters for unit tests. Junit has some handy annotations that help you with reading a CSV source and using its contents as parameters for a unit test.
To use these annotations, you need the following dependencies. The first one is for Junit itself and the second one is for the JUnit parameterized tests. This last dependency includes the annotations we need.
|
|
CSV source inside an annotation
If you don't have a lot of values you need to test you can put them inside the annotation like is done in the following example.
You need to place the two annotations on your test to make it work. @ParameterizedTest
tells JUnit that your tests need parameters to run.
The @CsvSource
lets you define what the parameters should be in CSV format.
|
|
CSV files as source
When you need a lot of values, and it gets too big or messy to define them inside the test class, you can also place them inside a file.
To do this you would need the @ParameterizedTest
to tell Junit that your tests need parameters. The @CsvFileSource
lets
you define which file you want to read the values from. In the following example the values from /values.csv
are used for the test.
The values.csv
file is placed inside the test/resource directory.
|
|
Array of CSV files as source
You can also use multiple CSV files as the source for a unit test. To use multiple CSV files you need to define them in an
array like this: resources = {"/values.csv", "/more-values.csv"}
. The following example reads the values from the following files: values.csv
and more-values.csv
.
|
|
The values.csv file
This is what the values.csv
file from the previous examples looks like:
Name,age
Noah,20
James,22
Evelyn,35
Harper,58
Conclusion
in this post, we took a look at how to read parameters for a unit test from a CSV file. The first example shows how to define and use a CSV array inside the test class. The example shows how to