Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduled method is called during the tests [duplicate]

I'm developing a SpringBoot application using Maven.

I've a class with the @Component annotation which has a method m with the @Scheduled(initialDelay = 1000, fixedDelay = 5000) annotation. Here fixedDelay can be set to specify the interval between invocations measured from the completion of the task.

I've also the @EnableScheduling annotation in the main class as:

@SpringBootApplication
@EnableScheduling
public class FieldProjectApplication {

    public static void main(String[] args) {
        SpringApplication.run(FieldProjectApplication.class, args);
    }

}

Now whenever I run the tests, defined as :

@RunWith(SpringRunner.class)
@SpringBootTest
public class BankitCrawlerTests {

...

}

the scheduled task m is also run every 5 seconds.

Of course I just want to run the scheduled task whenever the application runs. How can I do it (i.e. prevent the scheduled task to run when a test is run)?

like image 816
nbro Avatar asked Oct 24 '16 20:10

nbro


1 Answers

You can extract @EnableScheduling to a separate configuration class like:

@Configuration
@Profile("!test")
@EnableScheduling
class SchedulingConfiguration {
}

Once it's done, the only thing that is left is to activate "test" profile in your tests by annotating test classes with:

@ActiveProfiles("test")

Possible drawback of this solution is that you make your production code aware of tests.

Alternatively you can play with properties and instead of annotating SchedulingConfiguration with @Profile, you can make it @ConditionalOnProperty with property present only in production application.properties. For example:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Configuration
    @ConditionalOnProperty(value = "scheduling.enabled", havingValue = "true", matchIfMissing = true)
    @EnableScheduling
    static class SchedulingConfiguration {

    }
}

Scheduler will not run in tests when you do one of following:

  • add property to src/test/resources/application.properties:

    scheduling.enabled=false

  • customize @SpringBootTest:

    @SpringBootTest(properties = "scheduling.enabled=false")

like image 175
Maciej Walkowiak Avatar answered Nov 15 '22 17:11

Maciej Walkowiak