Step by step tutorial on java rest assured framework using cucumber by maven

install rest assured and cucumber maven dependencies

  1. Open IntelliJ
  2. Go to File > New > Project
  3. Select Maven
  4. Click on the Next button
  5. Give the project name and click on the Finish button
  6. Now open pom.xml file
  7. Add following dependencies:
<dependencies>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>2.3.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>2.3.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>4.3.3</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>
        <dependency>
            <groupId>commons-configuration</groupId>
            <artifactId>commons-configuration</artifactId>
            <version>1.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

8. Now import all of the dependencies

Create feature file

9. Now expand test folder under src
10. Create a new directory named resources
11. Right-click on resources folder and set mark directory as
Test Resources Root
12. Now create a file named customers.feature under resources folder.
Write following context:

Feature: Customer API Testing

  Scenario: Calling login API
    Given Login API is provided
    When User call login API
    Then a token will be generated
  Scenario: Calling customer list API
    Given Customer list API is provided
    When User call customer list API
    Then Customer list will be shown
  Scenario: Calling customer get API
    Given Customer get API is provided
    When User call customer get API
    Then Specific customer info will be shown

Generate cucumber step definitions

13. Now create a class named RunCucumberTest under src /test/java folder

14. Write following code:

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

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty","html:target/cucumber-reports/cucumber.html",
        "json:target/cucumber-reports/cucumber.json"})
public class RunCucumberTest {
}

15. Now select RunCucumberTest class and right click to start run cucumber test

16. You will see that steps definitions has been generated in response console

Configure properties file

17. Now create a file named config.properties under src/test/resources folder

18. Write our API baseUrl here:

baseUrl=https://customer-test-api.herokuapp.com

19. Now create a class named Utils

20. Here we will write some code so that we can save some of the environment variables. After calling login API, a token will be generated. So, we will save the token in the config.properties file so that we can use the token later.

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import java.io.IOException;

public class Utils {
    public static String setEnvVariable(String variable) throws IOException, ConfigurationException {
        PropertiesConfiguration config = new PropertiesConfiguration("./src/test/resources/config.properties");
        config.setProperty("token", variable);
        config.save();
        return variable;

    }
}

21. Now create a class named StepDefinitions under src/test/java folder

22. Copy paste the step definitions under StepDefinitions class

23. Now add this code under StepDefinitions class so that we can load the baseUrl from config.properties file

Properties prop=new Properties();
    FileInputStream file;
    {
        try
        {
            file = new FileInputStream("./src/test/resources/config.properties");
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

24. And Remove the throw new PendingException(); from every step definitions as this is no longer needed

import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;

public class StepDefinitions {
    Properties prop=new Properties();
    FileInputStream file;
    {
        try
        {
            file = new FileInputStream("./src/test/resources/config.properties");
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    @Given("^Login API is provided$")
    public void login_API_is_provided() throws Exception {
        // Write code here that turns the phrase above into concrete actions
    }

    @When("^User call login API$")
    public void user_call_login_API() throws Exception {
        // Write code here that turns the phrase above into concrete actions
    }

    @Then("^a token will be generated$")
    public void a_token_will_be_generated() throws Exception {
        // Write code here that turns the phrase above into concrete actions
    }

    @Given("^Customer list API is provided$")
    public void customer_list_API_is_provided() throws Exception {
        // Write code here that turns the phrase above into concrete actions
    }

    @When("^User call customer list API$")
    public void user_call_customer_list_API() throws Exception {
        // Write code here that turns the phrase above into concrete actions
        
    }

    @Then("^Customer list will be shown$")
    public void customer_list_will_be_shown() throws Exception {
        // Write code here that turns the phrase above into concrete actions
        
    }

    @Given("^Customer get API is provided$")
    public void customer_get_API_is_provided() throws Exception {
        // Write code here that turns the phrase above into concrete actions
        
    }

    @When("^User call customer get API$")
    public void user_call_customer_get_API() throws Exception {
        // Write code here that turns the phrase above into concrete actions
        
    }

    @Then("^Specific customer info will be shown$")
    public void specific_customer_info_will_be_shown() throws Exception {
        // Write code here that turns the phrase above into concrete actions
        
    }
}

Calling API

23. Now we will do some code for each step definitions with Rest Assured Framework to call API’s

25. This is the full code in the StepDefinitions class:

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import io.restassured.RestAssured;
import io.restassured.http.Header;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.json.JSONObject;
import org.junit.Assert;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;

public class StepDefinitions {
    Properties prop=new Properties();
    FileInputStream file;
    {
        try
        {
            file = new FileInputStream("./src/test/resources/config.properties");
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    RequestSpecification request;
    @Given("^Login API is provided$")
    public void login_API_is_provided() throws Exception {
        prop.load(file);
        RestAssured.baseURI  = prop.getProperty("baseUrl");
        request = RestAssured.given();

    }
    Response response;
    @When("^User call login API$")
    public void user_call_login_API() throws Exception {
        JSONObject requestParams = new JSONObject();
        requestParams.put("username", "salman");
        requestParams.put("password", "salman1234");
        request.header("Content-Type", "application/json");
        System.out.print(request.body(requestParams.toString()));
        response = request.post("/customer/api/v1/login");

    }

    @Then("^a token will be generated$")
    public void a_token_will_be_generated() throws Exception {
        int statusCode = response.getStatusCode();
        System.out.println(statusCode);
        System.out.print(response.asString());
        String token= response.jsonPath().getString("token");
        System.out.println(token);
        Utils.setEnvVariable(token);

    }

    @Given("^Customer list API is provided$")
    public void customer_list_API_is_provided() throws Exception {
        prop.load(file);
        RestAssured.baseURI  = prop.getProperty("baseUrl");
        request = RestAssured.given();

    }

    @When("^User call customer list API$")
    public void user_call_customer_list_API() throws Exception {
        Header authorizationHeader = new Header("Authorization", prop.getProperty("token"));
        request.header(authorizationHeader);
        response = request.get("/customer/api/v1/list");
    }

    @Then("^Customer list will be shown$")
    public void customer_list_will_be_shown() throws Exception {
        System.out.println("Response Body is =>  " + response.asString());
        String customerId=response.jsonPath().getString("Customers[0].id");
        Assert.assertEquals(customerId,"101");

    }

    @Given("^Customer get API is provided$")
    public void customer_get_API_is_provided() throws Exception {
        prop.load(file);
        RestAssured.baseURI  = prop.getProperty("baseUrl");
        request = RestAssured.given();

    }

    @When("^User call customer get API$")
    public void user_call_customer_get_API() throws Exception {
        Header authorizationHeader = new Header("Authorization", prop.getProperty("token"));
        request.header(authorizationHeader);
        response = request.get("/customer/api/v1/get/101");

    }

    @Then("^Specific customer info will be shown$")
    public void specific_customer_info_will_be_shown() throws Exception {
        System.out.println("Response Body is =>  " + response.asString());
        String customerId=response.jsonPath().getString("id");
        Assert.assertEquals(customerId,"101");

    }
}

26. Now click on the run button. You will see 3 scenario and 9 steps has been passed. Also, a token has been generated and saved to config.properties file

Report Generate

27. Now add following plugins in pom.xml file

<plugins>
            <plugin>
                <groupId>net.masterthought</groupId>
                <artifactId>maven-cucumber-reporting</artifactId>
                <version>5.3.0</version>
                <executions>
                    <execution>
                        <id>execution</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <configuration>
                            <projectName>Sample-Cucumber-TestNG</projectName>
                            <skip>false</skip>
                            <outputDirectory>reports/html-reports</outputDirectory>
                            <inputDirectory>target/cucumber-reports</inputDirectory>
                            <jsonFiles>
                                <param>**/*.json</param>
                            </jsonFiles>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>

28. Import the packages

29. give following command:
mvn clean install

30. reports folder will be generate and you will find the html report to this location:
reports\html-reports\cucumber-html-reports

Here is the full project:
https://github.com/salmansrabon/java-rest-assured-cucumber-demo

about author

admin

salmansrabon@gmail.com

If you like my post or If you have any queries, do not hesitate to leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *