Arkadiusz Kwiatkowski
Software Tester Lead
Reviewed by a tech expert

Automated services tests

#Sales
#Sales
#Sales
#Sales
Read this articles in:
EN
PL

In this article, you’ll read how to automate the testing process of a backend service. There are multiple approaches, techniques, and tools available, but we will focus on one of the most basic approaches. To automate our backend service, we’ll use REST Assured (http://rest-assured.io) with Java, and the TestNG framework for test management.

REST Assured is in fact a library containing tools that you can use to send, validate, and configure backend requests in Java in a simple and user-friendly manner.

For the tests, we will use the public API http://dummy.restapiexample.com/, as it does not require authorisation.

To begin your backend tests, you need to create a new maven project in your compiler. Add required libraries in the pom.xml file to import them (the pom file should resemble the screenshot below).

Pom.xml dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>org.example</groupId>
   <artifactId>apiTest</artifactId>
   <version>1.0-SNAPSHOT</version>
<dependencies>
   <dependency>
       <groupId>org.testng</groupId>
       <artifactId>testng</artifactId>
       <!-- last used testNG 6.14.3 -->
       <version>7.0.0</version>
   </dependency>
   <dependency>
       <groupId>io.rest-assured</groupId>
       <artifactId>rest-assured</artifactId>
       <version>3.3.0</version>
       <scope>test</scope>
   </dependency>
</dependencies>
</project>

In your new project, create a new class in the src/test/java directory (in our case, the class is called RestAssuredTest) to store your tests in.

New class location

new class location - RestAssuredTest

This is an example of endpoint response (http://dummy.restapiexample.com/api/v1/employees)

An example of API response

// GET http://dummy.restapiexample.com/api/v1/employees
{
 "status": "success",
 "data": [
   {
     "id": "1",
     "employee_name": "Tiger Nixon",
     "employee_salary": "320800",
     "employee_age": "61",
     "profile_image": ""
   },
   {
     "id": "2",
     "employee_name": "Garrett Winters",
     "employee_salary": "170750",
     "employee_age": "63",
     "profile_image": ""
   }
 ]
}

First test — getting data from API

Using the tools provided in the REST assured library, we will create our first test to check if the number of registered workers is higher than zero. How to do that?

  • Import when() method and use an appropriate method to specify the request type you want to submit. We pass into the method the URL to which you want to send your request to.
  • In the then() section, you can prepare response verification.
  • In the example below, we verify the correctness of the server response using the statusCode() method. To do that, we pass the anticipated response code into the method.
  • Then, with the use of the body() method we verify the content of the response. By specifying the field in the response (using JsonPath), we can conduct simple assertions. In this case, I specified the data field and used the .size() method to check the size of the array. Next, using the greaterThan() method you can verify if the field contains at least one element.

First test

import io.restassured.http.ContentType;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;

public class RestAssuredTest {
   String url = "http://dummy.restapiexample.com/api/v1/";

   @Test
   public void getEmployeesContainsAtLeastOneEmployee() {
       when()
               .get(url + "employees")
       .then()
               .log().all()
               .statusCode(200)
               .body("data.size()", greaterThan(0));
   }
}

If you want to verify your response from the received request, you can add the log().all() method, which prints the response to the console

An example of information printed from the console logger

Second test — sending data to API

Another test that we’re about to automate is responsible for creating a new user. After verifying the information from the documentation (http://dummy.restapiexample.com/create), we can see that in order to create a new user, you need to submit the body utilizing the post method.

  • So, I pass the body to the given() method in the form of a string, and I specify the contentType.
  • In the when section, I specify that the request should be sent using the post method.
  • I perform simple assertions to verify if the username matches the submitted body and if the status is a success

Test of sending data to API

@Test
public void createNewEmployee() {
       String bodyToSend= "{" +
               "\"name\":\"Arek\"," +
               "\"salary\":\"99999\"," +
               "\"age\":\"29\"" +
               "}";

       given()
               .body(bodyToSend)
               .contentType("application/json")
       .when()
               .post(url + "create")
       .then()
               .statusCode(200)
               .body("status", equalTo("success"))
               .body("data.name", equalTo("Arek"));
   }

Third test — passing data between requests

Now, let’s create a more complex test to forward information from one request to another for verification.

  • At the beginning, I create a new user with a slight change, and I declare an int variable, employeeId,
  • I add the extract() method at the end of the request, which allows me to extract any field from the response into a variable using the path() method and by specifying the field using the JsonPath standard.

Now, we send a query regarding a specific user utilizing the returned id field by using the get endpoint (http://dummy.restapiexample.com/api/v1/employee/{id})

A test where data is forwarded from one response to another

@Test
public void getNewCreatedEmployee() {
       String bodyToSend= "{" +
               "\"name\":\"Darek\"," +
               "\"salary\":\"91999\"," +
               "\"age\":\"94\"" +
               "}";

       int employeeId = given()
               .body(bodyToSend)
               .contentType("application/json")
       .when()
               .post(url + "create")
       .then()
               .statusCode(200)
               .body("status", equalTo("success"))
               .body("data.name", equalTo("Darek"))
       .extract()
               .path("data.id");

       when()
               .get(url + "employee/"+employeeId)
       .then()
               .statusCode(200)
               .body("data.id", equalTo(employeeId))
               .body("data.name", equalTo("Darek"));
   }

Obviously, the body in rest assured requests can be also sent using objects, or the entire body can be exported to a previously prepared object, but this is a topic for another part of the backend testing series. The examples above are only an introduction to automated backend tests / automated service tests.

Hello!Have you ever wondered what can be done to eliminate manual tests of your backend services, while paying attention to the responses they return?

People also ask

No items found.
Want more posts from the author?
Read more

Want to read more?

Web

Post-deployment application performance monitoring

If you're a member of a development team (particularly a tester), this place is perfect for you. At a certain stage of the project, you publish the application.
No results found.
There are no results with this criteria. Try changing your search.
en