Let’s say we have to create Test Automation Framework to test a Web Service.

Assumptions:

  • Our Web Service (API) is REST API
  • By default we set Content-type and Accept Http request headers to application/json
  • We do not test request/response headers. On real projects we have to test headers as well, especially for API Gateways where headers can contain very important information
  • To simplify our goal we will test for example Book Service that provides the simple CRUD functionality. CRUD - Create, Retrieve, Update and Delete books in our system.

Book.java

public class Book {
    private String id;
    private String title;
    private String author;

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    // getters and setters
}

Http Client

Http Request and Http Response

The first thing that you need to create the Test Framework for REST API testing is the Http Client. Once we create the Http Client we are able to call the REST Web Service that needs to be tested to actually test it. So let’s do the first step on the way to create the Test Framework - create the Http Client.

Our Http Client should provide at least four Http Methods - GET, POST, UPDATE and DELETE. These four cover more than 99% of all Http requests in real web services.

We’re going to use Apache Http Components. See previous posts related to that

Apache Http Client Maven dependency

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>

Also we want to implement Http Client as a Spring Boot component to be able autowire it in any place in our tests where we need.

This is how HttpClient might look like

HttpClient.java

Each of Http methods returns org.apache.http.HttpResponse. That class allows us to get the response payload.

Http Client usage

Let’s see how that Http Client can be used. To start using the client we have to autowire it like this

@Autowired
HttpClient http;

Here is the example that demonstrates the scenario:

  • 1. Call POST to create a book.
  • 2. Call GET to get all books.
  • 3. Call UPDATE to update an existing book.
  • 4. Call GET to get a book by id
  • 5. Call DELETE to delete a book.

Http Client in TestNG tests with Spring Boot

All you need now is to add your assertions to verify responses


You may also find these posts interesting: