Scheduled method is called during the tests [dupli

2019-04-22 21:46发布

问题:

This question already has an answer here:

  • Disable @EnableScheduling on Spring Tests 5 answers

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)?

回答1:

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")