Partner – Microsoft – NPI (cat= Spring)
announcement - icon

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

And, the Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

You can also ask questions and leave feedback on the Azure Spring Apps GitHub page.

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:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <relativePath/>
</parent>

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

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

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
</dependency>

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:

<dependency>
    <groupId>org.awaitility</groupId>
    <artifactId>awaitility</artifactId>
    <version>3.1.6</version>
    <scope>test</scope>
</dependency>

3. Simple @Scheduled Sample

Let’s start by creating a simple Counter class:

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

    @Scheduled(fixedDelay = 5)
    public void scheduled() {
        this.count.incrementAndGet();
    }

    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:

@Configuration
@EnableScheduling
@ComponentScan("com.baeldung.scheduled")
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:

@SpringJUnitConfig(ScheduledConfig.class)
public class ScheduledIntegrationTest {

    @Autowired 
    Counter counter;

    @Test
    public void givenSleepBy100ms_whenGetInvocationCount_thenIsGreaterThanZero() 
      throws InterruptedException {
        Thread.sleep(100L);

        assertThat(counter.getInvocationCount()).isGreaterThan(0);
    }
}

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:

@SpringJUnitConfig(ScheduledConfig.class)
public class ScheduledAwaitilityIntegrationTest {

    @SpyBean 
    private Counter counter;

    @Test
    public void whenWaitOneSecond_thenScheduledIsCalledAtLeastTenTimes() {
        await()
          .atMost(Duration.ONE_SECOND)
          .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:

>> THE COURSE
res – REST with Spring (eBook) (everywhere)
2 Comments
Oldest
Newest
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.