Step-by-Step Guide to API Automation Framework with Rest-Assured, Java, and Cucumber

Step-by-Step Guide to API Automation Framework with Rest-Assured, Java, and Cucumber

Introduction

Rest-Assured is a popular Java library for testing and validating RESTful APIs, known for its simplicity and powerful features. Cucumber, on the other hand, is a Behavior-Driven Development (BDD) tool that allows writing test cases in plain English, making them accessible to non-technical stakeholders.

By combining these tools, this guide aims to help you build a robust and maintainable API automation framework. You will learn how to:

  1. Set up your project environment.
  2. Create and manage dependencies using Maven.
  3. Write and execute API tests using Rest-Assured.
  4. Integrate Cucumber to write readable and maintainable test scenarios.
  5. Structure your project for scalability and efficiency.

Whether you are a beginner or an experienced automation engineer, this guide will equip you with the knowledge and tools necessary to automate API testing effectively, ensuring higher quality and faster delivery of your software products.


Prerequisites

  1. Java Development Kit (JDK): Install JDK 8 or higher.
  2. Maven: Install Maven for dependency management.
  3. IDE: Use an IDE like IntelliJ IDEA or Eclipse.

Step 1: Set Up Your Project

  1. Create a new Maven project: In your IDE, create a new Maven project.
  2. Add dependencies to pom.xml: Include the necessary dependencies for Rest-Assured, Cucumber, JUnit, and Maven Surefire plugin.

xml
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>api-automation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- JUnit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- Rest-Assured -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>4.3.3</version>
            <scope>test</scope>
        </dependency>
        <!-- Cucumber -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>6.10.4</version>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>6.10.4</version>
            <scope>test</scope>
        </dependency>
        <!-- Gson for JSON parsing -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
                <configuration>
                    <includes>
                        <include>**/*Test*.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>        

Step 2: Project Structure

Create the following directory structure in your project:

src
├── main
│   └── java
│       └── com
│           └── example
│               └── api
│                   ├── utils
│                   ├── models
│                   └── steps
└── test
    └── java
        └── com
            └── example
                └── api
                    ├── runner
                    └── features        

Step 3: Create Feature Files

  1. Create a Cucumber feature file in 'src/test/java/com/example/api/features/Example.feature':

gherkin
Feature: API Testing with Rest-Assured and Cucumber

Scenario: Get user details
    Given I set the base URI to "https://reqres.in"
    When I send a GET request to "/api/users/2"
    Then the response status code should be 200
    And the response should contain the user's details        

Step 4: Implement Step Definitions

  1. Create a Step Definitions file in 'src/main/java/com/example/api/steps/ApiSteps.java':

java
package com.example.api.steps;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.rest-assured.RestAssured;
import io.rest-assured.response.Response;

import static org.hamcrest.Matchers.equalTo;

public class ApiSteps {
    private Response response;

    @Given("I set the base URI to {string}")
    public void setBaseUri(String baseUri) {
        RestAssured.baseURI = baseUri;
    }

    @When("I send a GET request to {string}")
    public void sendGetRequest(String endpoint) {
        response = RestAssured.get(endpoint);
    }

    @Then("the response status code should be {int}")
    public void verifyStatusCode(int statusCode) {
        response.then().statusCode(statusCode);
    }

    @Then("the response should contain the user's details")
    public void verifyUserDetails() {
        response.then().body("data.id", equalTo(2));
        response.then().body("data.email", equalTo("[email protected]"));
        response.then().body("data.first_name", equalTo("Janet"));
        response.then().body("data.last_name", equalTo("Weaver"));
    }
}        

Step 5: Create a Test Runner

  1. Create a Test Runner file in 'src/test/java/com/example/api/runner/TestRunner.java':

java
package com.example.api.runner;

import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/java/com/example/api/features",
    glue = {"com.example.api.steps"},
    plugin = {"pretty", "html:target/cucumber-reports.html"},
    monochrome = true
)
public class TestRunner {
}        

Step 6: Running the Tests

To execute your tests, run the TestRunner class. This will trigger the Cucumber test run, which will read the feature files, match the steps to the definitions, and execute the tests using Rest-Assured.


Framework Details

Directory Structure:

  • main/java/com/example/api/utils: Contains utility classes for common functions.
  • main/java/com/example/api/models: Contains POJO classes for JSON request/response bodies.
  • main/java/com/example/api/steps: Contains the step definitions.
  • test/java/com/example/api/runner: Contains the test runner class.
  • test/java/com/example/api/features: Contains the Cucumber feature files.


Dependency Management:

  • Managed through Maven, defined in 'pom.xml'.


Test Execution:

  • Executed through JUnit using the TestRunner class.


Assertions:

  • Done using Rest-Assured's then() method to validate response status codes and body content.


Reporting:

  • Cucumber's built-in HTML reporting plugin is used for generating test reports.

Conclusion

This guide provides a comprehensive framework setup for API automation using Rest-Assured, Java, and Cucumber. By following these steps, you can create a robust and maintainable test automation framework that leverages the power of Cucumber for BDD and Rest-Assured for API testing.

Feel free to expand this framework by adding more utility functions, handling complex JSON structures, and integrating with CI/CD pipelines for continuous testing. Happy testing!

要查看或添加评论,请登录

Keshab Fouzdar的更多文章

社区洞察

其他会员也浏览了