Even though there are several REST API Testing Frameworks available in the market today, they may not always suite your application, or may need modifications based on your requirements. This may call for the creation of your own rest testing framework.
We will be creating a simple Rest Testing Framework in Java and JUnit that could be used for any testing scenarios.
Rest Testing Framework Overview
The framework should be able to execute the basic REST operations (GET, POST, PUT, PATCH, DELETE) and perform the validations on the code, message, headers and body of the response.
The completed code can be accessed from my GitHub account from where you can collect and make modifications based on your requirements.
Design
We will be having three classes for the framework (in packagecom.axatrikx.controller)
RestExecutor : Performs the HTTP operations using Apache Http Client
RestResponse : A javabean class to hold our response values (code, message, headers, body)
RestValidator : Validates the response with the expected values
The package com.axatrikx.test holds the test scripts.
Note: I will be using ‘json-server‘ to fake the REST API. Its a real handy tool to rapidly setup fake REST API for testing your framework.
We are planning to have the framework implementation in the way shown below.
// Get operation with validations
executor.get(“/posts/1”)
.expectCode(200)
.expectMessage(“OK”)
.expectHeader(“Content-Type”, “application/json; charset=utf-8”)
.expectInBody(“userId”);
RestResponse
Its a JavaBean class holding the values from the response for each request. Four variables are provided each having its own getters and setters. See the class here.
public class RestResponse {
private int responseCode;
private String responseBody;
private HashMap<String, String> headers;
private String responseMessage;public RestResponse() {
headers = new HashMap<String, String>();
}public int getResponseCode() {
return responseCode;
}
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
public String getResponseBody() {
return responseBody;
}
public void setResponseBody(String responseBody) {
this.responseBody = responseBody;
}
public HashMap<String, String> getHeaders() {
return headers;
}
public String getHeader(String name) {
return headers.get(name);
}
public void setHeader(String name, String value) {
this.headers.put(name, value);
}
public String getResponseMessage() {
return responseMessage;
}
public void setResponseMessage(String responseMessage) {
this.responseMessage = responseMessage;
}
}
RestValidator
This class performs the validation of the response with the expected values. It takes a RestResponse object in its constructor.
It has a method for each type of validations performed and all the methods returns the same object reference which enables chaining possible. The assertions are done using Junit assertions. See the class here.
The code is self explanatory and I’ve added a printBody() method to print the response body during script creation or debugging. This method also returns the Validator object and therefore can be used in the chain at any point.
import java.util.Set;
import org.junit.Assert;public class RestValidator {private RestResponse response;
RestValidator(RestResponse response) {
this.response = response;
}
public RestValidator expectCode(int expectedCode) {
Assert.assertEquals(“Incorrect Response Code”, expectedCode, response.getResponseCode());
return this;
}
public RestValidator expectMessage(String message) {
Assert.assertEquals(“Incorrect Response Message”, message, response.getResponseMessage());
return this;
}
public RestValidator expectHeader(String headerName, String headerValue) {
Assert.assertEquals(“Incorrect header – ” + headerName, headerValue, response.getHeader(headerName));
return this;
}
public RestValidator expectHeaders(HashMap<String, String> headers) {
Set<String> keys = headers.keySet();
for (String key : keys) {
Assert.assertEquals(“Incorrect header – ” + key, headers.get(key), response.getHeader(key));
}
return this;
}
public RestValidator expectInBody(String content) {
Assert.assertTrue(“Body doesnt contain string : ” + content,
response.getResponseBody().contains(content));
return this;
}
public RestValidator printBody(){
System.out.println(response.getResponseBody());
return this;
}
public RestResponse getResponse(){
return response;
}
}
RestExecutor
This class performs the HTTP operations using Apache HttpClient library and would be having a method for each of the operations. We will look into two methods in detail an you can check the code for the rest.
Constructor
The constructor is a simple one which takes in the url and initilizes the HttpClient object.
private String url;public RestExecutor(String url) {
client = HttpClientBuilder.create().build();
this.url = url;
}
The GET method would have the path as one parameter and a HashMap as the second parameter for the headers provided as key value pairs. The method would be returning a RestValidator object containing the values corresponding to the response values of the GET request.
HttpGet request = new HttpGet(url + path);
HttpResponse response;
/*
* The response object which holds the details of the response.
*/
RestResponse resResponse = new RestResponse();
StringBuffer responseString = new StringBuffer();
try {
/*
* Setting the headers for the request
*/
if (headers != null) {
Set<String> keys = headers.keySet();
for (String key : keys) {
request.addHeader(key, headers.get(key));
}
}
/*
* Executing the GET operation
*/
response = client.execute(request);/*
* Obtaining the response body from the response stream.
*/
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = “”;
while ((line = rd.readLine()) != null) {
responseString.append(line);
}
/*
* Setting values for the response object
*/
resResponse.setResponseBody(responseString.toString());
resResponse.setResponseCode(response.getStatusLine().getStatusCode());
resResponse.setResponseMessage(response.getStatusLine().getReasonPhrase());
Header[] rheaders = response.getAllHeaders();
for (Header header : rheaders) {
resResponse.setHeader(header.getName(), header.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
/*
* Returns the RestValidator object providing the response object
*/
return new RestValidator(resResponse);
}
The HttpGet method is initialized with the combined URL, headers are set and request is executed to obtain the response. The response is then processed into our RestResponse object taking in our required values. This response object is used to initialize a RestValidator object corresponding to this GET request which is returned to the user to perform validations.
return get(path, null);
}
POST Method
Post Method is similar to the GET method above, the only difference being the presence of xml body.
HttpPost post = new HttpPost(url + path);
RestResponse resResponse = new RestResponse();
StringBuffer responseString = new StringBuffer();
try {
if (headers != null)
post.setEntity(getEntities(headers));/*
* Setting the xml content and content type.
*/
StringEntity input = new StringEntity(xmlContent);
input.setContentType(contentType);
post.setEntity(input);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = “”;
while ((line = rd.readLine()) != null) {
responseString.append(line);
}
resResponse.setResponseBody(responseString.toString());
resResponse.setResponseCode(response.getStatusLine().getStatusCode());
resResponse.setResponseMessage(response.getStatusLine().getReasonPhrase());
Header[] rheaders = response.getAllHeaders();
for (Header header : rheaders) {
resResponse.setHeader(header.getName(), header.getValue());
}
} catch (Exception e) {
e.printStackTrace(); // handle
}
return new RestValidator(resResponse);
}
A simpler POST method without headers is also provided.
For the remaining methods, check out the complete class.
Now that the core of our framework is done, lets see how to write the test scripts.
TestScript
Since we are using jUnit as the unit testing framework, we can initialize the RestExecutor object in the @BeforeClass method and use the object in the @Test methods.
import org.junit.Test;
import com.axatrikx.controller.RestExecutor;public class TestScript {
private static final String URL = “http://localhost:3000”;
private static RestExecutor executor;@BeforeClass
public static void setUp() {
/*
* Initialize RestExecutor object using the end point URL
*/
executor = new RestExecutor(URL);
}
@Test
public void testGETMethod() {
/*
* Performs GET operation on http://localhost:3000/posts.
* Note that we give only the path in the get method as we use
* the domain part while initializing the RestExecutor object
*/
executor.get(“/posts”)
.expectCode(200) // Expected code of 200
.expectMessage(“OK”) // Expected Message of ‘OK’
.expectHeader(“Content-Type”, “application/json; charset=utf-8”) // Content-Type header value
.expectInBody(“rest testing framework”) // Content inside the response body
.expectInBody(“webdriver framework”) // Another Content inside the response body
.expectInBody(“axatrikx”); // Yet Another Content inside the response body
/*
* GET for a specific item
*/
executor.get(“/posts/1”)
.expectCode(200)
.expectMessage(“OK”)
.expectHeader(“Content-Type”, “application/json; charset=utf-8”)
.expectInBody(“rest testing framework”)
.expectInBody(“axatrikx”);
/*
* GET for a seach query
*/
executor.get(“/posts?title=rest%20testing%20framework&author=axatrikx”)
.expectCode(200)
.expectMessage(“OK”)
.expectHeader(“Content-Type”, “application/json; charset=utf-8”)
.expectInBody(“rest testing framework”)
.expectInBody(“axatrikx”);
}
@Test
public void testPOSTMethod() {
/*
* POST operation for insertion providing the path, xml content and content type.
*/
executor.post(“/posts”, “{ \”title\”: \”new test\”, \”author\”: \”axatrikx\” }”, “application/json”)
.expectCode(201)
.expectMessage(“Created”)
.expectHeader(“Content-Type”, “application/json; charset=utf-8”)
.expectInBody(“\”title\”: \”new test\””)
.expectInBody(“axatrikx”);
}
}
The executor.get(“/posts”) returns the RestValidator object having the RestResponse corresponding to the request. We can use the various validation methods on the object to perform the validation. As you might have noticed in RestValidator class, the assertions are using junit with the error messages preset. The remaining validations will be skipped if any one of the validations fail. Again, this can be modified according to your needs.
The same method is followed in the post request for the second @Test method. I haven’t added a proper reporting mechanism for this framework, but you can use any reporting libraries for JUnit or create one on your own.
See the completed project in github.
I’d suggest to make this framework as Generic so that this can be used project independent. You can refer my article Most commonly used methods
Suggested: Basic concepts of API, API Testing using Selenium WebDriver And Java
Author: Amal Bose Reference: Axatrikx.com
Thanks for sharing Charan
LikeLiked by 1 person
Hello Charan,
Thanks for the article. I am newbie in API testing and programming. I downloaded your source code but no idea how can I run this.
Can you please throw some light on that. Also how I can use json-server?
Thanks,
LikeLike
You can integrate the API’s you need to test. For example, if you send a post request, what response should be shown! Just a hint though
LikeLike
Please share your email. Need some inputs on Automating the Rest API Tests.
mail to [email protected]
LikeLike
Hi, you can reach me on [email protected]
LikeLike
For this purposes, I used http://rest-assured.io/
It helped me to decide many tasks
LikeLike
Yea, I do agree. Thanks for sharing though.
LikeLike
Thanks Charan for posting such an useful article. Can you always please provide some similar framework where we parameterize JUnit tests from Excel and run the tests please
LikeLike
A good, framework for testing with api, i have adapted all your framework for a usage with cucumber tests…
However i have to investigate how i can use the method post, patch, delele and getentities, the method get was very easy by your example…
I have to check the other methods.
Regards,
LikeLike
Great article!!!!
LikeLike
Nice article!!! I was exploring on API testing using selenium and your article came in handy. Can this work on TestNG? do we need to change anything to make it work on TestNG
LikeLike
Hi Charan, Nice article. I was looking for API testing using selenium and this came in handy. What change to do to work on TestNg?
LikeLike
No, this can be integrated with any other frameworks. You need to use OOPS if you’re tying with functional part
LikeLike
How to give authentication in header here?
LikeLike
The api works fine when given as url on a browser but I get SSL exception when tried to do this through httpurlclient/httpget/httpclient using selenium.
Is there some setting that i need to take care?
LikeLike
How do i post Multi Array Json? in below mentioned format.
(“/posts”, “{\”token\”:”+passtoken+” , \”id\”:\”49602\”}”, “application/json”)
LikeLike
Hi,can you please provide me input files ,which one are you using json or xml
LikeLike
You can try with your API, URL mentioned in the article was loopback address. This program supports Json
LikeLike
Hi Charan,
Can you please let me know how to validate the json response using JasonObject class.
LikeLike
Are you looking for a snippet?
LikeLike
hey nice article but can you please tell how i can use ‘json-server’ . i have download the package for the same link you given above but not get exact way and pleade give complete details for ‘json-server’ that to add this in the same project(your project which is downloaded from git).
LikeLike
I recommend using Automated REST API Testing Tools like vREST (https://vrest.io).. It requires lesser time and also that it has a great support team backing it!
LikeLiked by 1 person
Thanks for sharing with us. I would also recommend Katalon Studio since most I’ve received many recommendations from people using it
LikeLike
This is an awesome article. Love the simplicity of the design.
LikeLike