在测试期间调用计划的方法 [英] Scheduled method is called during the tests

查看:167
本文介绍了在测试期间调用计划的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Maven开发SpringBoot应用程序。

I'm developing a SpringBoot application using Maven.

我有一个带有 @Component 注释的类,其方法 m 使用 @Scheduled(ini​​tialDelay = 1000,fixedDelay = 5000)注释。这里 fixedDelay 可以设置为指定从完成任务开始测量的调用之间的间隔。

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.

我还在主类中的 @EnableScheduling 注释:

@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 {

...

}

预定任务 m 也是每5秒运行一次。

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

推荐答案

你可以提取 @EnableScheduling 到一个单独的配置类,如:

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

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

一旦完成,唯一剩下的就是通过用以下内容注释测试类来激活测试中的test配置文件:

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.

或者你可以使用属性而不是用 @Profile 来调用 SchedulingConfiguration code>,你可以使它 @ConditionalOnProperty ,其属性仅出现在生产 application.properties 中。例如:

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:


  • 将属性添加到 src / test / resources / application.properties

scheduling.enabled = false

scheduling.enabled=false

自定义 @SpringBootTest

@SpringBootTest(properties =scheduling.enabled = false)

这篇关于在测试期间调用计划的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆