Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Unit Testing With @Async Calls

DZone 's Guide to

Unit Testing With @Async Calls

Employing the @Async functionality can become tricky. And unit testing can become even more challenging.

· Java Zone ·
Free Resource

The use of asynchronous actions has been in play with client-based frameworks for several years. This same approach is becoming popular amongst Java-based frameworks. Spring provides the @Async (org.springframework.scheduling.annotation.Async) annotation as an entry point to such functionality.

While it may be easy to locate examples to guide one through the implementation of @Async functionality, adding unit test coverage may not be as easy to accomplish.

My goal with this article is to provide an example of unit testing @Async functionality.

The Disconnected Challenge

While working on a project that was employing a reactive approach on the client side, we discovered that there was a need to communicate "disconnected changes" to the client. What I mean by disconnected changes is mostly due to a data model that we could not change.

To provide an example, consider a scenario where the application is handling some aspect of publishing. After changes are committed to the publication, a preview is generated - similar to how Microsoft Word can save an image preview of documents (which is displayed when scanning documents from the file system). The disconnected challenge, in this case, was the timing on when the preview rendering finished. The design of the database not providing a direct link between the page and it's updated preview location rounded out the remainder of the disconnected challenge.

Due to this odd state, users were not seeing updated preview images unless they refreshed their browsers. This was not acceptable behavior.

The (Connected) Solution

Earlier in the project redesign, our team decided to utilize server-sent events (SSEs) to communicate changes in the application. Since this is a publication-based application, several users will be working on the same publication at any given time. As a result, changes will be occurring constantly. The expectation is that those changes simply appear before the user and do not require the user to refresh or reload the browser to see the changes.

The SSE implementation in place was monitoring JPA activities and will broadcast them to a message queue. That message queue would ingest the message, determine if the class containing the change could be converted into a DTO, which was expected by the client-based application. If so, the object was converted to a scaled-down DTO and sent as an SSE, which would then be updated in the reactive store within Angular running on each browser-based client session.

In this case, the disconnected updates could be discovered because there is a table in the application to store version information about each render event for the publication previews. The disconnected part is with the scaled-down versions (like thumbnail previews), which do not have a direct link to the publication page that needs a new preview. Again, this was due to a design in the database that could not be changed at this point.

Before sending the valid  Set<EventDto>eventDtos as an SSE, the following logic was added to the code:

processPagePreviewUpdates(documentId, eventDtos);


Which called this simple private method:

private void processPagePreviewUpdates(Long documentId, Set<EventDto> eventDtos) {
    if (indirectUpdateExists(eventDtos, ImageDto.class.getSimpleName()) {
        dtoChangeEventService.processIndirectPageUpdates(documentId, eventDtos);
    }
}


The boolean helper method uses a stream to determine if any of the elements in the  Set<EventDto>eventDtos are an instance of the ImageDto class.

private boolean indirectUpdateExists(Set<EventDto> eventDtos, String simpleClassName) {
    return eventDtos.stream()
            .filter(i -> i.getType().equals(simpleClassName))
            .count() > 0;
}


For those valid ImageDto elements, the processIndirectPageUpdates()  method uses the @Async  attribute, which will accomplish the following tasks:

  • Locate any page that uses the id provided within the ImageDto object

  • If a match is found, create a new EventDto that contains the page which has the new preview

  • Publish the EventDto as an SSE using a DtoChangeEvent class (designed to communicate non-JPA changes)

This is all at a high level to protect the intellectual property of the client.

The Unit Test

Creating the necessary unit test coverage for the @Async  method required implementing a pattern I had not seen before, using the verify()  method from Mockito.

Without getting into the protected code used on the project, the unit tests have the necessary when()  methods to setup mocked returns for services utilized by the system under test:

when(pageRepository.getPageByPreviewImageId(image.getId())).thenReturn(pageVO);
when(conversionService.convert(pageVO))).thenReturn(pageDto);


In the case of this example, the DtoChangeEvent being published has a void method return type. As a result, the doNothing() Mockito method was added to the tests:

doNothing().when(documentEventPublisher).publish(any(DocumentEvent.class), any(JmsHeaderDecorator.class));


Next, the service under test is called and the verify()  methods are introduced afterward, in order to give the @Async  functionality time to respond:

The verify()  method is constructed in a manner that includes the call portion of the mocked event and not the response that will be provided. That portion is already covered in the  when() method.

try {
    dtoChangeEventService.processIndirectPageUpdates(documentId, eventDTOs);

    verify(pageRepository, timeout(100).times(1)).getPageByPreviewImageId(image.getId());
    verify(conversionService, timeout(100).times(1)).convert(pageVO));

    assertTrue(true);
} catch (Exception e) {
    fail();
}


If these processes complete without any exceptions, I call the  assertTrue() method to mark the test as passed. Otherwise, the fail()method is called.

Had the original process returned values, the actual results could be compared against the mocked-up result set that was expected. These, of course, would replace the simple assertTrue(true)  line in the code.

Hope this helps and have a really great day!

Topics:
java ,async ,mockito ,spring ,unit testing ,server sent events ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}