Feeding Test Data from a CSV File into RestAssured Test Framework
Feeding test data from a CSV file into RestAssured is a common practice when we need to execute a large number of test cases with different input data. Here's an example of how to read test data from a CSV file and use it to execute RestAssured test cases:
Assume that we have a CSV file called "test_data.csv" with the following content:
username,password
john.doe,pass123
jane.doe,pass456
We can use the CSVReader
class from the OpenCSV library to read the CSV file and create test data objects for each row. Here's an example:
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.Test;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
public class APITest {
@Test
public void testLoginAPI() throws IOException, CsvException {
// Set the base URL for the API endpoint
RestAssured.baseURI = "https://example.com/api";
// Create a CSV reader to read the test data
CSVReader reader = new CSVReader(new FileReader("test_data.csv"));
// Read the CSV data into a list of arrays
List<String[]> data = reader.readAll();
// Loop through each row of data and execute the test case
for (String[] row : data) {
// Extract the test data from the row
String username = row[0];
String password = row[1];
// Send a POST request to the login API endpoint with the test data
Response response = RestAssured.given()
.param("username", username)
.param("password", password)
.post("/login");
// Check that the response status code is 200 (OK)
response.then().assertThat().statusCode(200);
// Add additional assertions as needed
}
}
}
In this example, we use the CSVReader
class to read the "test_data.csv" file and create a list of arrays containing the test data for each row. We then loop through each row of data, extract the test data from the row, and use it to execute a test case against the API. We can add additional assertions as needed to validate the response of the API for each test case.
Note that in this example we are using the param
method to pass the test data as query parameters in the API request. Depending on the API we are testing, we may need to use different methods to pass the test data, such as using the body
method to pass JSON or XML payloads.