Disable Spring @EnableScheduling in Junit tests

2019-07-23 00:00发布

问题:

I want to disable @Schedule in Spring tests but i can`t find a way to do it.

I have tried to make different config class for test environment but tasks are still fired. This is config:

@Configuration
@EnableTransactionManagement
@EnableScheduling
@ComponentScan({"de.package"})
@PropertySource(name="application.properties", value="classpath:application.properties")
public class PersistenceJPAConfig {
...
}

This is test emvironment config.Just removed @EnableScheduling annotation

@Configuration
@EnableTransactionManagement
@ComponentScan({"de.package"})
@PropertySource(name="application.properties", value="classpath:application.properties")
public class PersistenceJPATestConfig {
...
}

In test i use:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPATestConfig.class }, loader = AnnotationConfigContextLoader.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class GetArticlesTest {
...
}

But tasks are still fired when i run the test..Is there any way to stop executing tasks while running tests ?

回答1:

As you're using @ComponentScan on the same package both time, it seems spring is loading the other configuration too.

You could use some profile to filter that, like adding this on your PersistenceJPATestConfig

@Profile("test")

add this annotation on your JUnit class so it will be executed with the "test" profile

@ActiveProfiles("test")

Edit : Your main config should also be profiled so it is ignored when its profile is not active, so you should add another @Profile on the main config class with a different profile than "test"