Sometimes we need to execute a single test case multiple times.
In Java, For this purpose using JUnit's Parameterized testing is a good approach.
It allows us to provide test data in an iterable format and code runs for all the records. In this series, I will try to cover different ways of providing iterable data to unit tests.
In this tutorial, we will read the data from a CSV file with the annotation @CsvFileSource. It will use a comma-separated file as an input data source.
In Junit, We use the @Test annotation to mark a method as a test case. In case of making a test Parameterized, We need to add the annotation `@ParameterizedTest` instead of @Test and mention the input file as a parameter in `@CsvFileSource`.
@ParameterizedTest
@CsvFileSource(resources = "/input_test_data.csv", numLinesToSkip = 1)
You can see another parameter named 'numLinesToSkip' which is used to skip these lines for the testing. In this case, I have added 1 to skip the header name.
To start the example, First, create a CSV file under the directory 'src/test/resources' and name it whatever you want. For this example, the file name is "input_test_data" with two columns. i.e. First Name and Last Name. Following are the contents of our CSV file.
First Name, Last Name
Ragnar, Lothbrok
Now create a Java class in the test folder and put the following contents in the file.\
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
class ParameterizedUnitTest {
@ParameterizedTest
@CsvFileSource(resources = "/input_test_data.csv", numLinesToSkip = 1)
public void testCategories(String firstName, String lastName) {
System.out.print("Full Name is :"+firstName+" "+lastName);
}
}
No comments:
Post a Comment