Skip to main content

Testing Asynchronous APIs: Awaitility tutorial

Despite the growing popularity of test automation, most of it is still likely to be done on the frontend side of application. While GUI is a single layer that puts all the pieces together, focusing your automation efforts on the backend side requires dealing with distributed calls, concurrency, handling their diversity and integration.

Backend test automation is especially popular in the microservices architecture, with testing REST API’s. I’ve noticed that dealing with asynchronous events is particularly considered as challenging. In this article I want to cover basic usage of Awaitility – simple java library for testing asynchronous events. All the code examples are written in groovy and our REST client is Rest-Assured.

Synchronous vs Asynchronous 

In simple words, synchronous communication is when the API calls are dependent and their order matters, while asynchronous communication is when the API calls are independent. Quoting Apigee definition:

Synchronous 
If an API call is synchronous, it means that code execution will block (or wait) for the API call to return before continuing. This means that until a response is returned by the API, your application will not execute any further, which could be perceived by the user as latency or performance lag in your app. Making an API call synchronously can be beneficial, however, if there is code in your app that will only execute properly once the API response is received.

Asynchronous 
Asynchronous calls do not block (or wait) for the API call to return from the server. Execution continues on in your program, and when the call returns from the server, a “callback” function is executed.

Awaitility 

Awaitility is the JVM-based open-source library for verifying asynchronous calls. Let’s assume you’re publishing an event to the system:

publish(new event("Hello World"))

Since our event is asynchronous, we can’t synchronously block our test execution and wait for the event’s response. This’ll likely fail:

publish(new Event("Hello World"))
assert eventIsPublished() //likely to fail here

To handle this asynchronous check, we can wrap our assertion in the awaitility’s block and poll the resource for the event’s presence:

publish(new Event("Hello World"))
await().until(eventIsPublished())

By default, awaitility will wait for 10 seconds until eventIsPublished() is true. If not it’ll throw ConditionTimeoutException.

Installation 
In order to add awaitility to your classpath, you need to include its dependency. Since we want to implement our examples in Groovy, the library we’re looking for is: org.awaitility.awaitility-groovy. For maven users:

<dependency>
    <groupId>org.awaitility</groupId>
    <artifactId>awaitility-groovy</artifactId>
    <version>3.0.0</version>
</dependency>

For Gradle users:

compile group: 'org.awaitility', name: 'awaitility-groovy', version: '3.0.0'

To use Awaitility effectively it’s recommended to use static imports:

import static org.awaitility.Awaitility.*

Basic usage example 

Main goal of this article is to show how you can perform calls to asynchronous REST APIs in your tests. Imagine we have an RESTful resource: /deal, which is consuming asynchronous events. Subsequently, events are given unique dealId and you can request particular deal details with GET request on /deal/{dealId}. If there’s no (or not yet) deal with requested dealId, the response is HTTP code 404.

First thing we want to do is implement the REST client to /deal resource. Here’s the simple implementation with use of the REST-Assured library:


In the above implementation, we’re accessing deal/$dealId resource with GET method and returning extracted response object. The problem is the async nature of our service. We don’t know the exact time when the single deal is accessible – when there’s no deal our API is responding with 404, so the test like the one below would be highly non-deterministic.


How to handle this asynchronous events in our test? The solution comes with Awaitility’s library. In the second approach, we’re wrapping /deal request in await() method:


The method we will call in the test assertion is isPricePositive(). We’re using await() method there to poll for our asynchronous event. For this we’re using another helper method: is200(). This method calls our /deal client and if the response is 404 it returns false, if it’s not – it returns the response body. The third method is of course our REST client which stays exactly like the one implemented previously. The only change in our test is the then block, where we’re calling isPricePositive() assertion:


With this approach we’re handling all the issues with asynchronous calls to /deal resource, leaving test method clean, readable and – what’s the most important – deterministic.

Polling

There’s a list of settings which we can use to customise the await() calls. One of the most important are polling options, where we define the initial delay before polling begins and the interval between polls (poll interval). In the example below poll delay is 100ms and the poll interval is 200ms:


Awaitility has to offer much more in terms of polling options, check the documentation for more.

Defaults 

Having this variety of options, you can also define default values for polling, timeouts, etc. The snippet below shows an example implementation of defining default values in spock’s setupSpec block:


Better reuse 

In our example test, we used single-method condition in await() method. Awaitility also supports two parts conditions – supplying and matching:


Summary 

Test automation of the asynchronous systems and APIs can be challenging task, but with use of proper tools it can be also very rewarding. Above examples are just few use cases of implementing tests in groovy with Awaitility and Rest-Assured. I recommend you to use those frameworks for yourself and explore their possibilities. If you have any questions, feel free to leave a comment.

Popular posts from this blog

Test Automation: Good, Bad and Ugly

The modern approach to software quality and software development life cycle requires that business guys, developers and testers understand that the long manual test phase, although often still necessary, must be reduced to a minimum and replaced by test automation. Working in continuous delivery and continuous integration environment requires us to create automated tests that run on demand, checking our application integration and it’s core functionality correctness. However, there are still many problems with designing and writing automated tests, resulting in their costly maintenance or abandonment in favour of a return to manual processes.
In this article I will focus on describing common good practices of test automation. This post is more than an overview than complete reference guide. Broader aspects, such as the Page Object pattern or Page Factory will be described in detail in a separate article on this blog. Although most practices apply for every types of automated tests, thi…

REST-Assured framework overview

In modern software development, REST services becomes most popular choice for implementing distributed and scalable web application. They are light and easy to maintain, which results in faster and more effective implementation and system integration.
I recommend you also my other posts about REST-Assured and building microservice’s test automation frameworks: REST-Assured: going deeperBuilding microservices testing framework
With the increase popularity of RESTful services, there is a need for fast and lightweight tool for REST webservices testing automation. One of the most popular choice is Rest-Assured framework from Jayway. It introduces simplicity of testing web services from dynamic languages like groovy or ruby to java. In this post we will get our hands dirty and write automatic test in Rest-Assured framework.
In order to create complete implementation of automated tests in Rest-Assured framework, we need to write our code against some example API. We’ll use standalone Wiremock m…

REST-Assured: going deeper

In my previous post I described the basic REST-Assured usage – the lightweight framework for testing RESTful services. Despite the fact that described range of functionalities would be enough in most cases,REST-Assured has a lot more to offer. In this post I would like to bring some more advanced examples of the framework usage.



I recommend you also my other posts about REST-Assured and building microservice’s test automation frameworks:

REST-Assured – framework overviewBuilding microservices testing framework
Object Mapping Sending request’s body as string is easy and straightforward, but it can be inconvenient in the case of more complex operations on request / response properties. Proven solution for this is a good-known serialization of request/response body to objects. REST-Assured supports object mapping to (and from) JSON and XML. For JSON you need either to have Jackson or Gson in your classpath and for XML you need JAXB. Here is an example of request object serialization using J…