logo logo

7 Key Points For Automating Using Rest Assured

main post image

Testing RESTful applications has become a more pressing issue with “modern” approaches like test-driven development (TDD). Users started looking for a tool that could help with designing and running the tests as fast as possible, but with many options related to test execution environment. With organizations moving into Agile and TDD – early testing, increased test coverage and integration tests are the need of the hour. There are many ways to perform the REST API testing like using POSTMAN client, cURL, JMeter, SOAPUI. Apart from that, Java-based API test framework can be used (Apache HTTP Client, Jersey Test Framework and Rest assured).

In this article I will elaborate the key points that need to be considered while using Rest Assured, to keep our integration tests concise, clean, decoupled and maintainable.

1. Project Test Structure

  • Placing the integration test within the project folder (/src/test/java) and executing them during the build. For such an approach, there should be a clear demarcation between unit tests and integration tests. This approach doesn’t need a separate Jenkins job or a built pipeline, as it will execute the whole build including the tests. It may not work when one service has a dependency on others.
  • Separate the integration test project for each service. Here we do need a separate Jenkins job and a built pipeline, decoupling between the project and the integration tests.

2. Make your test more robust, it should not break if internal changes happen within the API (for instance, if a user is relying on the database of the service to create a test data, and suddenly the schema of the database changes, like changing from relational DB to Mongo DB).

3. Put reusable methods on common operations on the rest resource under abstract test class, which can be extended by the test class.

4. Create a RequestSpecification to reuse request configurations (base URL, parameters, content type, logging, session keys) that you want to use for all requests.

5. Create a separate POJO (Plain Old Java Object) class and use an ObjectMapper like Jackson to serialize Java objects into JSON and deserialize JSON string into Java objects. Rest-assured provides built-in support for object mapping. It is very useful to make a POST call.

Here’s an example of a POST call end point as /client and it accepts Client Type and Client ID as string as part of the request body:

 

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)

@JsonRootName("data")

public class Client {

@JsonProperty("type")

String type;

@JsonProperty("client_id")

String client_id;

public Client() {

  }

public void setClientType(String type) {

     this.type = type;

  }

public void setClientId (String client_id) {

     this.client_id = client_id;

  }

}

Test Class

@Test

public void testPostData()  {

//New Object for the type Client  
Client client = new Client();

//Set the request body of the Post Call with the test data
client.setDataType("Permanent");

client.setClientId("12345");

 Data dataObject = new Data(client);

//Object Mapper to serialize Java objects into JSON
ObjectMapper mapper = new ObjectMapper();

String categoryJson = mapper.writeValueAsString(dataObject);

//rest assured given mostly consists request header and request body 
given()

.contentType(ContentType.JSON)

.body(categoryJson)
// rest assured when depicts the end point of the API
.when()

.post("/client")

/* rest assured then validating the output, below we are validating with a response code 200 that means the test is successful. If the response code is not 200 then the test will fail */

. then()

.assertThat()

.statusCode(200);

}

The returned POJO’s can be validated by using Hamcrest matcher, but one can also use AssertJ library to write fluent, readable and type-safe test assertions. It should be mentioned that if a user is interested in a single value of a JSON response, creating a POJO class for mapping is a little bit of an overkill. Moreover, Rest Assured has a built-in support for JsonPath, but then you have to use Hamcrest matcher.

6. For an asynchronous event to take effect, users must poll until a certain condition becomes true. We can use Awaitility which provides a nice API to wait and poll until the assertion becomes true or a timeout exceeds. For example, posting a comment on FB and validating based on commentID.

7. OkHttp MockWebServer can be used to mock one service when it has a dependency on another service that is not yet developed. This gives you the flexibility to add the tests to your automation environment in the development process.   

What are your key points while using Rest Assured? You are welcome to join the discussion below  😉 

Vikas Kumar

About the author

Vikas Kumar

Vikas Kumar is a highly skilled and full stack QA Automation Engineer with 10 plus years of experience with expertise in Quality Assurance, Test Management, Automation and Release Management. Having a deep background in enterprise Software Quality Assurance, he leads QA teams in a diverse set of test activities including – Mobile SDK, Community Products for Web UI and API Testing, Platform Libraries, CPU Benchmarking, Performance and Virtualization technologies. He drives and delivers end to end test activities for the Agile model and has ability to build strong working relationships with business & technology stakeholders across geographies while championing continuous improvement initiatives.

Join TestProject Community

Get full access to the world's first cloud-based, open source friendly testing community. Enjoy TestProject's end-to-end test automation Platform, Forum, Blog and Docs - All for FREE.

Join Us Now  

Comments

22 1 comment
  • Avatar
    Andy Turfer July 17, 2019, 7:48 am

    Very nice simple example. Would have been very useful to perhaps use an example that’s a little more complicated (i.e. nested JSON arrays and objects).

Leave a Reply

Join TestProject Newsletter

Join a 20K community of readers! Always stay up-to-date with all the latest test automation trends, best practice and tips shared by leading software testing community experts across the globe!

FacebookLinkedInTwitterEmail