Spring framework exposes a nice feature to schedule some task: @Scheduled annotation. But these features make very difficult unit test process – all scheduled tasks start to work in any unit test where Spring scanning is used. It means
that You can not test only one method without execution all scheduled tasks.
In next sections I describe a demo project with solution of this problem.
This project demonstrates usage of Spring Boot framework. Main goal is to give an example of development and unit testing of Spring schedule feature.
The main problem with unit testing of schedule feature of the Spring framework is to prevent automatic execution of a scheduled methods in the tests. Automatic execution of a scheduled methods is nice feature for production but it does unit testing very problematic task. Developer do not want to execute all scheduled tasks in unit tests but to test a dedeicated methods only.
This demo projects shows how to achieve:
- use schedule feature of Spring framework
- prevent execution scheduled methods in unit tests
Project consists of:
- SomeService – a service which does some work
- SomeComponent – a component which uses SomeService; SomeComponent gets SomeService reference as autowired dependency
- Scheduling – holds configuration of scheduled services; Scheduling gets services via autowired Spring mechanism.
- Application – a configuration initialization
- ApplicationRunner – the application entry point
Unit tests are:
- SomeServiceTest – very simple test
- SomeComponentTest – this test demonstrates usage of the @ConditionalOnProperty annotation
In the production code, in the Scheduling class @ConditionalOnProperty specifies condition when to use @Scheduled annotation. By default the Scheduling class is in context and all methods with @Scheduled annotation will be scheduled.
In the test code, in the SomeComponentTest following code disables scheduling:
@TestPropertySource(properties = "app.scheduling.enable=false")
Project source on Java (JUnit4): https://github.com/ysden123/pspring/tree/master/scheduled-java
Project source on Java (JUnit5): https://github.com/ysden123/poc/tree/master/pjunit5/spring-boot-junit5
Project source on Scala: https://github.com/ysden123/pspring/tree/master/scheduled-scala