1. Introduction

One of the available annotations in the Spring Framework is @Scheduled. We can use this annotation to execute tasks in a scheduled way.

In this tutorial, we’ll explore how to test the @Scheduled annotation.

2. Dependencies

First, let’s start creating a Spring Boot Maven-based application from the Spring Initializer:


We’ll also need to use a couple of Spring Boot starters:


And, let’s add the dependency for JUnit 5 to our pom.xml:


We can find the latest version of Spring Boot on Maven Central.

Additionally, to use Awaitility in our tests, we need to add its dependency:


3. Simple @Scheduled Sample

Let’s start by creating a simple Counter class:

public class Counter {
    private AtomicInteger count = new AtomicInteger(0);

    @Scheduled(fixedDelay = 5)
    public void scheduled() {

    public int getInvocationCount() {
        return this.count.get();

We’ll use the scheduled method to increase our count. Note that we’ve also added the @Scheduled annotation to execute it in a fixed period of five milliseconds.

Also, let’s create a ScheduledConfig class to enable scheduled tasks using the @EnableScheduling annotation:

public class ScheduledConfig {

4. Using Integration Testing

One of the alternatives to test our class is using integration testing. To do that, we need to use the @SpringJUnitConfig annotation to start the application context and our beans in the testing environment:

public class ScheduledIntegrationTest {

    Counter counter;

    public void givenSleepBy100ms_whenGetInvocationCount_thenIsGreaterThanZero() 
      throws InterruptedException {


In this case, we start our Counter bean and wait for 100 milliseconds to check the invocation count.

5. Using Awaitility

Another approach to testing scheduled tasks is using Awaitility. We can use the Awaitility DSL to make our test more declarative:

public class ScheduledAwaitilityIntegrationTest {

    private Counter counter;

    public void whenWaitOneSecond_thenScheduledIsCalledAtLeastTenTimes() {
          .untilAsserted(() -> verify(counter, atLeast(10)).scheduled());

In this case, we inject our bean with the @SpyBean annotation to check the number of times that the scheduled method is called in the period of one second.

6. Conclusion

In this tutorial, we showed some approaches to test scheduled tasks using integration testing and the Awaitility library.

We need to take into account that, although integration tests are good, it’s generally better to focus on the unit testing of the logic inside the scheduled method.

As usual, all the code samples shown in this tutorial are available over on GitHub.

Course – LS (cat=Spring)

Get started with Spring and Spring Boot, through the Learn Spring course:

res – REST with Spring (eBook) (everywhere)
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.