DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Driving DevOps With Smart, Scalable Testing
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Practical Use of Weak Symbols
  • Generate Unit Tests With AI Using Ollama and Spring Boot

Trending

  • Bridging UI, DevOps, and AI: A Full-Stack Engineer’s Approach to Resilient Systems
  • What’s Got Me Interested in OpenTelemetry—And Pursuing Certification
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Unit Testing With @Async Calls

Unit Testing With @Async Calls

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

By 
John Vester user avatar
John Vester
DZone Core CORE ·
Jun. 19, 19 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
131.5K Views

Join the DZone community and get the full member experience.

Join For Free

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!

unit test

Opinions expressed by DZone contributors are their own.

Related

  • Driving DevOps With Smart, Scalable Testing
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Practical Use of Weak Symbols
  • Generate Unit Tests With AI Using Ollama and Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!