首页 > 其他分享 >单元测试-在弹簧测试上禁用@EnableScheduling

单元测试-在弹簧测试上禁用@EnableScheduling

时间:2023-06-18 11:33:28浏览次数:38  
标签:PACKAGE 禁用 app 单元测试 class AppConfiguration EnableScheduling import public

当我运行单元测试时,它会调用我的计划任务。 我想防止这种行为,这是由于我的主应用程序配置中包含@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);
    }
}

spring unit-testing junit junit4 springjunit4classrunner
Robbo_UK asked 2020-08-01T10:36:56Z
5个解决方案
42 votes
如果您不想使用配置文件,则可以添加标志以启用/禁用应用程序调度
在您的AppConfiguration中添加此
  @ConditionalOnProperty(
     value = "app.scheduling.enable", havingValue = "true", matchIfMissing = true
  )
  @Configuration
  @EnableScheduling
  public static class SchedulingConfiguration {
  }

在您的测试中,只需添加此注释即可禁用计划
@TestPropertySource(properties = "app.scheduling.enable=false")

Marko Vranjkovic answered 2020-08-01T10:37:24Z
11 votes
另一种选择是取消注册安排事件的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或确保PostProcessor的排序不会成为问题的可能的含义...
yankee answered 2020-08-01T10:37:49Z
9 votes
我只是用可配置的延迟时间参数化了@Scheduled注释:
@Scheduled(fixedRateString = "${timing.updateData}", initialDelayString = "${timing.initialDelay}")

在我的测试application.yaml中:
timing:
    updateData: 60000
    initialDelay: 10000000000

和主要application.yaml:
timing:
    updateData: 60000
    initialDelay: 1

它不是关闭它,而是造成了如此长的延迟,测试将在运行之前很长一段时间。 不是最优雅的解决方案,但绝对是我找到的最简单的解决方案之一。
Laila Sharshar answered 2020-08-01T10:38:22Z
2 votes
在每个测试中,您定义应使用的弹簧配置,当前您具有:
@ContextConfiguration(classes={AppConfiguration.class})

常见的做法是为正常应用和测试定义单独的弹簧配置。
AppConfiguration.java 
TestConfiguration.java

然后在测试中,您只需使用@ContextConfiguration(classes={TestConfiguration.class})即可引用TestConfiguration,而不是当前的AppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestConfiguration.class})
@Transactional
@TransactionConfiguration(defaultRollback = true)
@WebAppConfiguration
public class ExampleDaoTest

这样,您可以与生产代码中不同的方式为测试配置任何设置。 例如,您可以将内存数据库用于测试,而不是常规数据库。
Vojtech Ruzicka answered 2020-08-01T10:38:56Z
1 votes
通过创建一种在单元测试期间删除计划任务的方法,我能够解决此问题。这是一个例子:
    import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
    import org.springframework.context.ApplicationContext;

    public static void removeSchedulledTasks(ScheduledAnnotationBeanPostProcessor postProcessor, ApplicationContext appContext) {

    postProcessor.setApplicationContext(appContext);

    Iterator<ScheduledTask> iterator = postProcessor.getScheduledTasks().iterator();

    while(iterator.hasNext()) {

        ScheduledTask taskAtual = iterator.next();
        taskAtual.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 schedulled tasks method
        Utils.removeSchedulledTasks(postProcessor, appContext);

    }

    //Some test methods

}

希望这可以帮助。

标签:PACKAGE,禁用,app,单元测试,class,AppConfiguration,EnableScheduling,import,public
From: https://blog.51cto.com/u_16110904/6507903

相关文章

  • Chrome 禁用 javascript
    步骤1.打开控制台:右键>检查2.在控制台页面快捷键ctrl+shift+p然后输入javascript找到disabledjavaScript.解除禁用: ctrl+shift+p然后输入enablejavaScript找到enablejavaScrip. ......
  • 【gtest】Visual Studio 2019 单元测试学习Google Test
    前言记录在VS2019中使用自带的GoogleTest进行单元测试的方法和经验项目介绍总共2个项目,Work为项目工程,TestWork为Work工程的单元测试工程,TestWork依赖于Work工程,但是Work不依赖TestWork,TestWork是Work的旁路辅助工程,用于对代码的检查和测试。创建项目创建C++的常规Work工程......
  • iOS 单元测试之常用框架 OCMock 详解
    一、单元测试1.1单元测试的必要性测试驱动开发并不是一个很新鲜的概念了。在日常开发中,很多时候需要测试,但是这种输出是必须在点击一系列按钮之后才能在屏幕上显示出来的东西。测试的时候,往往是用模拟器一次一次的从头开始启动app,然后定位到自己所在模块的程序,做一系列的点击......
  • textBox禁用浏览器自动填充
    https://blog.csdn.net/jijunwu/article/details/20540769asp.Net设置 AutoCompleteType  属性 AutoCompleteType="Disabled"后台代码添加属性  textBoxId.Attributes.Add("autocomplete","off");......
  • Spartacus Storefront 里如何在 SmartEdit 访问环境下暂时禁用 Early login
    关于SpartacusEarlylogin的功能,即如果当前客户没有登录,则显示loginpage.而不是显示原始页面。有的客户期望Spartacus在SmartEdit环境下预览时,暂时禁掉这个功能。首先,开发人员应该分析与需求相关的所有后果并对安全威胁进行建模,然后考虑是否接受它们,例如:某些功能页......
  • Mac的IDEA配置Junit单元测试
    Junit使用步骤1.定义一个测试类(测试用例)规范建议:测试类命名:功能名称或者类名+Test包命名:xxx.xxx.xxx.test2.定义测试方法规范建议:方法名:test+被测试的方法名返回值:void参数列表:空参3.给方法加上注解@Test4.添加Junit的依赖环境添加Junit依赖环境前,输入@Test......
  • 玩转Google开源C++单元测试框架Google Test系列(gtest)(总)
    前段时间学习和了解了下Google的开源C++单元测试框架GoogleTest,简称gtest,非常的不错。我们原来使用的是自己实现的一套单元测试框架,在使用过程中,发现越来越多使用不便之处,而这样不便之处,gtest恰恰很好的解决了。其实gtest本身的实现并不复杂,我们完全可以模仿gtest,不断的完善我们......
  • 验签失败!单元测试成功!!究竟是啥坑?
    错误的入参:rawData===>  "{\"nickName\":\"拥有你便是拥有一切\",\"gender\":1,\"language\":\"zh_CN\",\"city\":\"Zhangjiakou\",\"province\":\"Hebei\",\&qu......
  • Linux 通过修改 grub 文件禁用节能模式
    1、执行vi/etc/default/grub命令以编辑该文件 将光标移至GRUB_CMDLINE_LINUX行,在rhgb前新增intel_idle.max_cstate=0intel_pstate=disable字段,输入wq命令,按回车即能保存退出。2、生成启动文件 3、将改动写入镜像 最后执行reboot或者shutdown-rnow命令来......
  • Junit单元测试:断言、小结
          ......