---
title: Stop snoozing your tests!
description: Learn to use CountDownLatch to control the flow of your asynchronous tests instead of using Thread.sleep()
image: https://blog.ippon.tech/hubfs/Imported_Blog_Media/TEST-Snooze-3.png
---

[Skip to main content](https://blog.ippon.tech/stop-snoozing-your-tests#main)

[![IpponLogoKleinBlue](https://blog.ippon.tech/hs-fs/hubfs/IpponLogoKleinBlue.png?width=219&height=64&name=IpponLogoKleinBlue.png) ![IpponLogoKleinBlue](https://blog.ippon.tech/hs-fs/hubfs/IpponLogoKleinBlue.png?width=219&height=64&name=IpponLogoKleinBlue.png) ![IpponLogoKleinBlue](https://blog.ippon.tech/hs-fs/hubfs/IpponLogoKleinBlue.png?width=168&height=49&name=IpponLogoKleinBlue.png) ![IpponLogoKleinBlue](https://blog.ippon.tech/hs-fs/hubfs/IpponLogoKleinBlue.png?width=168&height=49&name=IpponLogoKleinBlue.png)](https://ipponusa.com/)

- [Home](https://ipponusa.com)
- [Show submenu for About About](https://ipponusa.com/about-us) 
    - [Who We Are](https://ipponusa.com/who-we-are)
    - [Careers](https://ipponusa.com/careers)
    - [Show submenu for Our Partners Our Partners](https://ipponusa.com/our-partners/) 
          - [AWS](https://ipponusa.com/our-partners/aws/)
          - [Snowflake](https://ipponusa.com/our-partners/snowflake/)
          - [Databricks](https://ipponusa.com/our-partners/databricks/)
          - [Microsoft](https://ipponusa.com/our-partners/microsoft/)
- [Show submenu for Services Services](https://ipponusa.com/services) 
    - [Snowflake](https://ipponusa.com/service/snowflake-concierge/)
    - [Artificial Intelligence](https://ipponusa.com/service/artificial-intelligence/)
    - [Data & Analytics](https://ipponusa.com/service/data-analytics/)
    - [Cloud Strategy](https://ipponusa.com/service/cloud-strategy/)
    - [Platform Modernization](https://ipponusa.com/service/platform-moderization/)
    - [Product Innovation](https://ipponusa.com/service/product-innovation/)
    - [Operating Model](https://ipponusa.com/service/operating-model/)
- [Blogs](https://blog.ippon.tech/)
- [Success Stories](https://ipponusa.com/success-stories/)
- [Show submenu for Resources Resources](https://ipponusa.com/resources/) 
    - [eBooks](https://ipponusa.com/ebooks/)
    - [The Data Pour](https://info.ippon.tech/the-data-pour)
    - [Videos & Webinars](https://info.ippon.tech/videos-and-webinars)
    - [Media Center](https://ipponusa.com/media-center/)

Search

Open main navigation

Close main navigation

- [Home](https://ipponusa.com)
- Show submenu for About About 
  
    - About
    - [About](https://ipponusa.com/about-us)
    - [Who We Are](https://ipponusa.com/who-we-are)
    - [Careers](https://ipponusa.com/careers)
    - Show submenu for Our Partners Our Partners 
      
          - Our Partners
          - [Our Partners](https://ipponusa.com/our-partners/)
          - [AWS](https://ipponusa.com/our-partners/aws/)
          - [Snowflake](https://ipponusa.com/our-partners/snowflake/)
          - [Databricks](https://ipponusa.com/our-partners/databricks/)
          - [Microsoft](https://ipponusa.com/our-partners/microsoft/)
- Show submenu for Services Services 
  
    - Services
    - [Services](https://ipponusa.com/services)
    - [Snowflake](https://ipponusa.com/service/snowflake-concierge/)
    - [Artificial Intelligence](https://ipponusa.com/service/artificial-intelligence/)
    - [Data & Analytics](https://ipponusa.com/service/data-analytics/)
    - [Cloud Strategy](https://ipponusa.com/service/cloud-strategy/)
    - [Platform Modernization](https://ipponusa.com/service/platform-moderization/)
    - [Product Innovation](https://ipponusa.com/service/product-innovation/)
    - [Operating Model](https://ipponusa.com/service/operating-model/)
- [Blogs](https://blog.ippon.tech/)
- [Success Stories](https://ipponusa.com/success-stories/)
- Show submenu for Resources Resources 
  
    - Resources
    - [Resources](https://ipponusa.com/resources/)
    - [eBooks](https://ipponusa.com/ebooks/)
    - [The Data Pour](https://info.ippon.tech/the-data-pour)
    - [Videos & Webinars](https://info.ippon.tech/videos-and-webinars)
    - [Media Center](https://ipponusa.com/media-center/)
- Search
- [Contact Us](https://ipponusa.com/contact/)

[Contact Us](https://ipponusa.com/contact/)

# Stop snoozing your tests!

![Ben Scott](https://app.hubspot.com/settings/avatar/d41d8cd98f00b204e9800998ecf8427e)

 by [Ben Scott](https://blog.ippon.tech/author/ben-scott)

September 8, 2020

![Stop snoozing your tests!](https://blog.ippon.tech/hubfs/Imported_Blog_Media/TEST-Snooze-3.png)

[Software Craftsmanship](https://blog.ippon.tech/tag/software-craftsmanship/) [Testing](https://blog.ippon.tech/tag/testing/)

September 8, 2020

 

Using some form of sleep is one of the main reasons for flaky tests and for regression suites taking much longer than necessary. This blog will provide one approach I've used to test consumer/producers. This approach could be used for testing with any message bus or asynchronous methods with a call back.

The example project I'll be using as a demo is a simple Spring Boot project and will use [Spring's application event publisher](https://www.baeldung.com/spring-events?ref=blog.ippon.tech) as our example message bus.

## Message publisher

```
@Service
public class MessageService {

    ApplicationEventPublisher eventPublisher;

    public MessageService(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    @Async
    public void publishMessage(Message message) {
        Random rand = new Random();
        try {
            Thread.sleep(rand.nextInt(4000));
            eventPublisher.publishEvent(message);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
```

This is our simple event publisher, it takes a Message object, sleeps a random amount between 0 and 4 seconds and publishes the message. The sleep here is done for demonstration purposes and simulates something that takes a while to process so that the asynchronous method can return immediately to our test case.

## Testing

For testing this we will need two things: a test consumer, and a Spring Boot test.

Our test consumer will be a Spring component that lives in our test package. This is something often overlooked by developers. You can create custom Spring components that will not be packaged alongside your production code.

```
@Component
public class MessageConsumer {

    Message resultMessage;
    CountDownLatch countDownLatch;

    @EventListener
    public void consumeMessage(Message message) {
        resultMessage = message;
        countDownLatch.countDown();
    }

    public void resetMessage() {
        resultMessage = null;
    }

    public void resetCountDownLatch() {
        countDownLatch = new CountDownLatch(1);
    }

    public Message getResultMessage() {
        return resultMessage;
    }

    public CountDownLatch getCountDownLatch() {
        return countDownLatch;
    }
}
```

Our event listener does two things, it saves the content of the message to a class variable so that it's accessible via a getter, and it count downs our [CountDownLatch](https://www.baeldung.com/java-countdown-latch?ref=blog.ippon.tech). A CountDownLatch is a blocking mechanism used to synchronize threads so that 1 or more threads can resume based on when the CountDownLatch goes to 0. In our case we block our test thread when we publish the message, and it our consumer thread countdowns the latch when the event is processed allowing our test thread to resume and assert the result.

Finally our test:

```
@SpringBootTest
class MessageServiceTest {

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageConsumer messageConsumer;

    @BeforeEach
    public void beforeEach() {
        messageConsumer.resetMessage();
        messageConsumer.resetCountDownLatch();
    }

    @Test
    public void publishMessage() throws InterruptedException {

        Message message = new Message("source", "Hello World!");
        messageService.publishMessage(message);

        messageConsumer.getCountDownLatch().await(4, TimeUnit.SECONDS);

        assertNotNull(message);
        assertEquals(message.getMessage(), messageConsumer.getResultMessage().getMessage());
        assertEquals(message.getName(), messageConsumer.getResultMessage().getName());
    }
}
```

As we're using Spring's events we need to use @SpringBootTest to load up the Spring context. We also need two beans in this test, the subject of our test and our test helper.

Our test case is simple:

- We publish a message
- We wait up to 4 seconds by locking the thread with the CountDownLatch
- We assert that our message is what we expect

The advantage of using the CountDownLatch versus Thread.sleep() here is that the Latch will release the thread as soon as the message is consumed by our TestConsumer so our test can start asserting immediately.

The other advantage is we can control our the CountDownLatch's timeout to reflect the SLA of our system. For example, if we expect our publisher to be able to produce the message within 4 seconds and we receive the message after 5 seconds then the test failure points to a performance issue.

The code for this blog can be found [here](https://github.com/bescott1/snoozingTests?ref=blog.ippon.tech).

## Related Articles

##### [![Getting Your Application Started With WebFlux](https://blog.ippon.tech/hs-fs/hubfs/Webflux%20image%20(1).png?width=520&height=294&name=Webflux%20image%20(1).png) Spring • May 7, 2024 Getting Your Application Started With WebFlux 6 min read](https://blog.ippon.tech/getting-your-application-started-with-webflux)

##### [![Webflux - Starting your journey](https://blog.ippon.tech/hs-fs/hubfs/Untitled%20design.png?width=520&height=294&name=Untitled%20design.png) Ippon • March 19, 2024 Webflux - Starting your journey 6 min read](https://blog.ippon.tech/webflux-starting-your-journey)

##### [![Python in Production (Part 5 of 5)](https://blog.ippon.tech/hs-fs/hubfs/Imported_Blog_Media/Screenshot-2023-03-29-at-12_21_28-PM-3.png?width=520&height=294&name=Screenshot-2023-03-29-at-12_21_28-PM-3.png) Python • June 24, 2023 Python in Production (Part 5 of 5) 8 min read](https://blog.ippon.tech/python-in-production-part-5-of-5)

### Comments

### Subscribe to Our Blog!

Stay informed with the latest insights and updates by signing up for our weekly blog newsletter – delivered straight to your inbox!

[Back to blog homepage »](https://blog.ippon.tech/)

![IpponLogoKleinBlue](https://blog.ippon.tech/hs-fs/hubfs/IpponLogoKleinBlue.png?width=247&height=73&name=IpponLogoKleinBlue.png "IpponLogoKleinBlue")

Ippon is a consulting and expertise firm, who is convinced that technology is a source of progress for society. We help our clients leverage their digital assets to design an appropriate strategy and deploy their transformation roadmap at scale.

#### Navigation

- [Home](https://ipponusa.com/)
- [About](https://ipponusa.com/about-us/)
- [Services](https://ipponusa.com/services/)
- [Blogs](https://blog.ippon.tech/?__hstc=223043268.1036d82247623b329dfefe4e92697801.1714729179243.1714729179243.1714729179243.1&__hssc=223043268.2.1714729179244&__hsfp=803678701)
- [eBooks](https://ipponusa.com/ebooks/)
- [The Data Pour](https://info.ippon.tech/the-data-pour?__hstc=223043268.1036d82247623b329dfefe4e92697801.1714729179243.1714729179243.1714729179243.1&__hssc=223043268.2.1714729179244&__hsfp=803678701)

[Contact Us](https://ipponusa.com/contact/)

[Join Us](https://ipponusa.com/careers/)

#### Services

- [Data & Analytics](https://ipponusa.com/service/data-analytics/)
- [Cloud Strategy](https://ipponusa.com/service/cloud-strategy/)
- [Artificial Intelligence](https://ipponusa.com/service/artificial-intelligence/)
- [Operating Model](https://ipponusa.com/service/operating-model/)
- [Platform Modernization](https://ipponusa.com/service/platform-moderization/)
- [Product Innovation](https://ipponusa.com/service/product-innovation/)

#### Ippon International

- [France](https://fr.ippon.tech/?__hstc=223043268.1036d82247623b329dfefe4e92697801.1714729179243.1714729179243.1714729179243.1&__hssc=223043268.2.1714729179244&__hsfp=803678701)
- [Australia](https://au.ippon.tech/?__hstc=223043268.1036d82247623b329dfefe4e92697801.1714729179243.1714729179243.1714729179243.1&__hssc=223043268.2.1714729179244&__hsfp=803678701)

- #### Contact
- Ippon Technologies  
  [3431 West Leigh Street Richmond, VA 23230, USA](https://maps.app.goo.gl/RySm6SAwZnsxeiLz9)
-  
- [(844) 477- 6687](tel:8444776687)
-  
- [Sales@ipponusa.com](mailto:Sales@ipponusa.com)

<https://www.facebook.com/IpponUSA/> <https://www.youtube.com/c/ipponusa> <https://www.linkedin.com/company/ippon-technology>

©Copyright 2024 Ippon USA. All Rights Reserved.   |   [Terms and Conditions](https://ipponusa.com/privacy-policy/)   |   [Privacy Policy](https://ipponusa.com/privacy-policy/)   |   [Website by Skol Marketing](https://skolmarketing.com/)

```json
{
  "@context" : "https://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "Ben Scott",
    "url" : "https://blog.ippon.tech/author/ben-scott"
  },
  "dateModified" : "2024-01-29T16:56:38.442Z",
  "datePublished" : "2020-09-08T12:56:00.000Z",
  "headline" : "Stop snoozing your tests!",
  "image" : [ "https://blog.ippon.tech/hubfs/Imported_Blog_Media/TEST-Snooze-3.png" ],
  "mainEntityOfPage" : {
    "@id" : "https://blog.ippon.tech/stop-snoozing-your-tests",
    "@type" : "WebPage"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://blog.ippon.tech/hubfs/logo_SVG.svg"
    },
    "name" : "Ippon Technologies"
  }
}
```