Let’s say we have to create Test Automation Framework to test a Web Service.
- Our Web Service (API) is REST API
- By default we set
AcceptHttp request headers to
- 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.
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
- POST HTTP request with Apache Http Client
- GET HTTP request with Apache Http Client
- PUT and DELETE HTTP requests with Apache Http Client
Apache Http Client Maven 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
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
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: