72

当我运行单元测试时,它会调用我的计划任务。我想防止这种行为,这是由于我@EnableScheduling在我的主应用程序配置上的事实造成的。

如何在我的单元测试中禁用它?

我遇到了这个建议设置配置文件的 问题/答案?

不知道我会怎么做?或者如果它是一个矫枉过正?我正在考虑为我的单元测试使用单独的 AppConfiguration,但是当我这样做时感觉就像我重复了两次代码?

@Configuration
@EnableJpaRepositories(AppConfiguration.DAO_PACKAGE)
@EnableTransactionManagement
@EnableScheduling
@ComponentScan({AppConfiguration.SERVICE_PACKAGE,
                AppConfiguration.DAO_PACKAGE,
                AppConfiguration.CLIENT_PACKAGE,
                AppConfiguration.SCHEDULE_PACKAGE})
public class AppConfiguration {

    static final    String MAIN_PACKAGE             = "com.etc.app-name";
    static final    String DAO_PACKAGE              = "com.etc.app-name.dao";
    private static  final  String ENTITIES_PACKAGE  = "com.etc.app-name.entity";
    static final    String SERVICE_PACKAGE          = "com.etc.app-name.service";
    static final    String CLIENT_PACKAGE           = "com.etc.app-name.client";
    static final    String SCHEDULE_PACKAGE         = "com.etc.app-name.scheduling";


    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
       // stripped code for question readability
    }

    // more app config code below etc

}

单元测试示例。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={AppConfiguration.class})
@Transactional
@TransactionConfiguration(defaultRollback = true)
@WebAppConfiguration
public class ExampleDaoTest {

    @Autowired
    ExampleDao exampleDao;

    @Test
    public void testExampleDao() {
        List<Example> items = exampleDao.findAll();
        Assert.assertTrue(items.size()>0);
    }
}
4

9 回答 9

78

如果您不想使用配置文件,您可以添加将启用/禁用应用程序调度的标志

在你AppConfiguration添加这个

  @ConditionalOnProperty(
     value = "app.scheduling.enable", havingValue = "true", matchIfMissing = true
  )
  @Configuration
  @EnableScheduling
  public static class SchedulingConfiguration {
  }

并在您的测试中添加此注释以禁用调度

@TestPropertySource(properties = "app.scheduling.enable=false")
于 2017-03-04T15:01:35.910 回答
24

我只是用可配置的延迟时间参数化了我的 @Scheduled 注释:

@Scheduled(fixedRateString = "${timing.updateData}", initialDelayString = "${timing.initialDelay}")

在我的测试 application.yaml 中:

timing:
    updateData: 60000
    initialDelay: 10000000000

和主要的application.yaml:

timing:
    updateData: 60000
    initialDelay: 1

它并没有关闭它,而是造成了如此长的延迟,测试将在它运行之前很久就结束了。不是最优雅的解决方案,但绝对是我发现的最简单的解决方案之一。

于 2018-07-29T19:14:02.850 回答
17

另一种方法是取消注册调度事件的 bean 后处理器。这可以通过简单地将以下类放在测试的类路径中来完成:

public class UnregisterScheduledProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (String beanName : beanFactory.getBeanNamesForType(ScheduledAnnotationBeanPostProcessor.class)) {
            ((DefaultListableBeanFactory)beanFactory).removeBeanDefinition(beanName);
        }
    }
}

虽然这很简单并且似乎可以完成这项工作,但请注意,我没有对此进行太多测试或检查从注册表中删除定义的 bean 或确保 PostProcessors 的排序不会成为问题的可能影响......

于 2017-01-10T10:58:05.923 回答
14

另一种解决方案,无需更改生产代码,使用@MockBean.

@RunWith(SpringRunner.class)
@SpringBootTest
@MockBean(MyScheduledClass.class)
public class MyTest {

最终将取代活动的预定作业或创建一个模拟作业。

从文档

Mocks 可以按类型或 {@link #name() bean name} 注册。在上下文中定义的任何现有的相同类型的单个 bean 都将被 mock 替换,如果没有定义现有的 bean,则将添加一个新的 bean。

于 2020-05-12T13:09:50.947 回答
8

使用 Spring Boot 和 cron 表达式,您可以启用或禁用调度。例如,您可以定义一个测试 application.yml 并设置

scheduler:
  cron-expr: '-'

另请参阅使用 '-' 禁用调度。在您的调度程序类中,您可以传递表达式。

@Scheduled(cron = "${scheduler.cron-expr}")
于 2020-09-28T15:52:19.867 回答
3

发现添加

app.scheduling.enable=false

在测试 application.properties 以及

@ConditionalOnProperty(value = "app.scheduling.enable", havingValue = "true", matchIfMissing = true)
@EnableScheduling

安排像Marko Vranjkovic's answer中的配置类注释适用于所有测试,而无需对每个测试进行注释!

于 2021-10-12T12:53:00.253 回答
2

在每个测试中,您定义应该使用哪个弹簧配置,目前您有:

@ContextConfiguration(classes={AppConfiguration.class})

通常的做法是为您的正常应用程序和测试定义单独的弹簧配置。

AppConfiguration.java 
TestConfiguration.java

然后在您的测试中,您只需引用TestConfiguration而不是当前AppConfiguration使用@ContextConfiguration(classes={TestConfiguration.class})

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestConfiguration.class})
@Transactional
@TransactionConfiguration(defaultRollback = true)
@WebAppConfiguration
public class ExampleDaoTest

通过这种方式,您可以为测试配置与生产代码不同的任何设置。例如,您可以使用内存数据库进行测试,而不是常规数据库等等。

于 2015-03-12T16:20:00.777 回答
2

我能够通过创建一个在单元测试期间删除计划任务的方法来解决这个问题。这是一个例子:

    import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
    import org.springframework.context.ApplicationContext;

    public static void removeScheduledTasks(ScheduledAnnotationBeanPostProcessor postProcessor, ApplicationContext appContext) {
        postProcessor.setApplicationContext(appContext);
        postProcessor.getScheduledTasks().forEach(ScheduledTask::cancel);   
    }
}

使用示例:

import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.example.Utils;


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

    
    @Autowired
    private ScheduledAnnotationBeanPostProcessor postProcessor;
    
    @Autowired
    private ApplicationContext appContext;


    @Before
    public void init(){

        //Some init variables
        
        //Remove scheduled tasks method
        Utils.removeScheduledTasks(postProcessor, appContext);
        
    }

    //Some test methods

}

希望这可以帮助。

于 2019-01-02T12:51:12.300 回答
1

我希望在普通课程(不是单元测试)中做到这一点。我有我的主要 Spring Boot 应用程序,但需要一个小型实用程序类来进行一些批量数据清理。我想使用我的主应用程序的完整应用程序上下文,但关闭任何计划任务。对我来说最好的解决方案类似于 Gladson Bruno:

scheduledAnnotationBeanPostProcessor.getScheduledTasks().forEach(ScheduledTask::cancel);

这种方法的另一个优点是您可以获得所有计划任务的列表,并且您可以添加逻辑来取消某些任务但不能取消其他任务。

于 2021-07-27T21:25:31.233 回答