Skip to main content

Day 7: Writing data-driven tests

Day 7: Writing data-driven tests

Day 7 of Rest Assured training focuses on writing data-driven tests.

Data-driven testing is a technique used in software testing where test cases are designed to test the same functionality using different sets of input data. This approach allows us to test a wide range of scenarios and edge cases with minimal effort.

In Rest Assured, data-driven tests can be written using test data stored in external files such as CSV, Excel, or JSON files. The data is then read into the test script and used to perform API testing.

By using data-driven testing, we can easily cover various scenarios without duplicating test cases or writing additional test scripts. This technique also helps to reduce the effort required to create and maintain test cases, as we can simply update the test data instead of updating the entire test script.

In summary, data-driven testing allows us to test the same functionality with multiple sets of input data, providing comprehensive test coverage with minimal effort. Rest Assured provides several methods to implement data-driven testing in API automation testing, such as reading test data from external files and using it in test scripts.

Learn how to write data-driven tests using Rest Assured Data-driven testing is a technique where you can run the same test case with different input data to ensure that the application is behaving as expected. This technique is particularly useful when you have a large set of inputs to test and manually testing each input is impractical.

Rest Assured provides a simple way to implement data-driven tests by using external data sources such as Excel spreadsheets, CSV files, and databases. In this way, you can easily test different scenarios by simply changing the data in the external data source.

To write a data-driven test using Rest Assured, you need to follow these steps:

  1. Prepare your data source: You can use an Excel spreadsheet, a CSV file, or a database table to store your test data. The data source should contain all the input data that you want to test, along with the expected output for each input.

  2. Set up Rest Assured: You need to set up Rest Assured in your testing environment to be able to write and run tests. This involves adding the necessary dependencies to your project and creating a base URI and base path for your API.

  3. Read the data from the data source: You need to use a library such as Apache POI or OpenCSV to read the data from the data source into your test code.

  4. Write the test code: Once you have the data, you can write the test code using Rest Assured. You can use a loop to iterate through the data, sending a request to the API with each set of input data and verifying the response against the expected output.



  5. Here is an example of a data-driven test using Rest Assured and a CSV file as the data source:

    
         @Test
    public void testGetUserDetails() throws IOException {
        // Read data from CSV file
        CSVReader reader = new CSVReader(new FileReader("testdata.csv"));
        String[] line;
        List data = new ArrayList<>();
        while ((line = reader.readNext()) != null) {
            data.add(line);
        }
        reader.close();
    
        // Send request and validate response for each set of data
        for (String[] userData : data) {
            String userId = userData[0];
            String expectedName = userData[1];
            String expectedEmail = userData[2];
    
            given()
                .pathParam("userId", userId)
            .when()
                .get("/users/{userId}")
            .then()
                .statusCode(200)
                .body("name", equalTo(expectedName))
                .body("email", equalTo(expectedEmail));
        }
    }
    
         
    

    In this example, the test reads data from a CSV file called testdata.csv which contains user IDs, expected names, and expected email addresses for each user. The test sends a GET request to the API for each user ID in the CSV file and verifies that the response contains the expected name and email address.

    Data-driven testing can save a lot of time and effort when testing APIs with large sets of input data. By using Rest Assured, you can easily implement data-driven tests in your API testing strategy.



    Use techniques such as parameterization and iteration to test different scenarios

    When testing an API, it's important to test different scenarios to ensure that the API behaves correctly under different conditions. One way to achieve this is by using data-driven testing, which allows you to run the same test with different sets of data. This helps you to cover more test cases and identify potential issues that may not be apparent when testing with just one set of data.

    Parameterization is a technique that allows you to run the same test with different input values. For example, if you are testing an API that accepts a user ID as input, you can create a parameterized test that runs the same test with different user IDs. This allows you to test the API with different input values without having to create a separate test for each input value.

    Iteration is another technique that allows you to run the same test multiple times with different input values. This can be useful when you want to test the API with a range of values, such as testing a range of user IDs. With iteration, you can specify a starting value, an ending value, and a step value, and the test will run for each value in the specified range.

    Here's an example of how you can use data-driven testing with Rest Assured:

    Suppose you are testing an API that returns information about a user based on their ID. You want to test the API with different user IDs to ensure that it returns the correct information for each user.

    First, you can create an Excel sheet or CSV file that contains a list of user IDs:

    
         user_id
    12345
    67890
    23456
    
    
         
    

    Then, you can create a parameterized test that reads the user IDs from the Excel sheet or CSV file and runs the test with each user ID:

    
    @Test
    @CsvFileSource(resources = "/user_ids.csv")
    public void testGetUserById(String userId) {
        given()
            .pathParam("id", userId)
        .when()
            .get("/users/{id}")
        .then()
            .statusCode(200)
            .body("id", equalTo(userId));
    }
      
    

    In this example, the @CsvFileSource annotation reads the user IDs from the user_ids.csv file and passes each user ID as a parameter to the test method. The test method uses the given() method to set the user ID as a path parameter and sends a GET request to the API endpoint. Finally, the test method uses the then() method to validate that the response has a status code of 200 and that the id field in the response body is equal to the user ID. br>
    This is just one example of how you can use data-driven testing with Rest Assured. The same approach can be used with different types of data sources and different test scenarios.



    Examples
    
    @Test
    @CsvFileSource(resources = "/data.csv", numLinesToSkip = 1)
    public void testAddition(int num1, int num2, int result) {
        given()
            .param("num1", num1)
            .param("num2", num2)
        .when()
            .get("/addition")
        .then()
            .statusCode(200)
            .body("result", equalTo(result));
    }
    
      
    


    
    @Test
    public void testSquare() {
        List numbers = Arrays.asList(2, 4, 6, 8, 10);
        for (int number : numbers) {
            given()
                .param("number", number)
            .when()
                .get("/square")
            .then()
                .statusCode(200)
                .body("result", equalTo(number * number));
        }
    }
      
    

Comments

Popular posts from this blog

How to integrate Autoit with selenium

For handling Dialog boxes which are not web based, Then Autoit is the best Tool to handle this These are the following code should written in Selenium Selenium Code: try { String[] commands = new String[] {}; commands = new String[] { "Path" }; // location of Autoit EXE file Runtime.getRuntime().exec(commands); } catch (IOException e) { } Autoit code: if WinWaitActive("File Upload") Then ;MsgBox(2,"window found","Found the window") WinActivate("File upload") Send("!n") Sleep(5000) Send("File path") SEND("{ENTER}") ;location of the file you want to a to the form and submit ;Send("!O") Else MsgBox(1,"TimeOut","Timed out") EndIf Here we need to create a Exe file for the Autoit script and that path should be mentioned in selenium code.

Reflection API

The Reflection API allows Java code to examine classes and objects at run time.The new reflection classes allow you to call another class's methods dynamically at run time. With the reflection classes, you can also examine an instance's fields and change the fields' contents. The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method, Constructor, Array, and Modifier. Example program: import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; // calling method whose name we store in a variable public class ReflectionAPI { public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { String x="sampleTest"; //String meth=read name from xls file Method method= ReflectionAPI.class.getMethod(x, String.class); method.invoke(method, "welcome"); System.out.

Collection API

CollectionAPI: The Java Collections API's provide Java developers with a set of classes and interfaces that makes it easier to handle collections of objects. In a sense Collection's works a bit like arrays, except their size can change dynamically, and they have more advanced behaviour than arrays. Example program: import java.util.ArrayList; import java.util.Hashtable; public class CollectionAPI { /** * @param args */ public static void main(String[] args) { int names[] = new int[5]; ArrayList list = new ArrayList (); list.add("Ramu");//0 list.add("Venu");//1 list.add("Raju");//2 System.out.println(list.size()); for(int i =0; i<=list.size(); i++) { System.out.println(list.get(i)); } // key - value // key - unique Hashtable table = new Hashtable (); table.put("name", "Hyderabad"); table.put("place", "Mumbai"); table.put("na