Spring启动禁用@EnableAsync进行集成测试

psv*_*psv 8 integration-testing spring-test-mvc spring-boot

我想@EnableAsync在运行集成测试时禁用.

我试图覆盖配置文件,该文件使用@EnableAsync我的测试包中具有相同名称的类进行注释,但它不起作用.

在本主题中:是否可以在集成测试期间禁用Spring的@Async?

我看到了:

您可以...创建测试配置或使用SyncTaskExecutor简单地覆盖任务执行程序

但我不明白该怎么做.

有什么建议?谢谢

Ily*_*sev 16

您链接的主题确实提供了一个很好的解决方案

要创建SyncTaskExecutorfor测试,请确保实际具有spring上下文的测试配置类.请参考Spring文档:https: //docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

在此配置类中添加一个新bean:

@Bean
@Primary
public TaskExecutor taskExecutor() {
    return new SyncTaskExecutor();
}
Run Code Online (Sandbox Code Playgroud)

应该这样做!

注意不要在实时配置中创建这个bean!

  • 我最后要做的是在AsyncConfiguration类上添加一个@Profile(“!test”)`。谢谢 (2认同)

Dón*_*nal 10

如果运行测试时使用唯一的配置文件名称(例如“test”),则在运行测试时禁用异步的最简单方法是

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableAsync;


@Profile("!test")
@Configuration
@EnableAsync
public class AsyncConfiguration {

}
Run Code Online (Sandbox Code Playgroud)

就我而言,我必须添加以下内容src/test/resources/application.yml以确保测试在名为“test”的配置文件下运行

spring:
  profiles:
    active: test
Run Code Online (Sandbox Code Playgroud)