【问题标题】:Spring boot test with @DirtiesContext BEFORE_CLASS使用@DirtiesContext BEFORE_CLASS 进行春季启动测试
【发布时间】:2016-03-03 19:31:52
【问题描述】:

您好,我最近更新了我的 Spring Boot 应用程序并注意到新功能 (DirtiesContext.ClassMode.BEFORE_CLASS),这似乎符合我的需求,因为我在使用带注释 @RabbitListener 的方法重新加载 bean 时遇到了问题,出于某种原因 Spring 重新加载了该 bean ,但老豆被用作兔子听众。 (见here

我的代码:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes ={ServerConfig.class,ServerThroughAMQPBrokerRabbitMQIntegrationTestConfig.class})
@Category({IntegrationTest.class})
@TestPropertySource("classpath:test.properties")
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@TestExecutionListeners(listeners = {DirtiesContextBeforeModesTestExecutionListener.class, DirtiesContextTestExecutionListener.class})
public class ServerThroughAMQPBrokerRabbitMQIntegrationTest {

添加 DirtiesContext.ClassMode.BEFORE_CLASS 后 Spring 停止从以下位置加载 bean 的问题:

@SpringApplicationConfiguration(classes ={ServerConfig.class,ServerThroughAMQPBrokerRabbitMQIntegrationTestConfig.class})

所以问题:

我应该如何使用 DirtiesContext.ClassMode.BEFORE_CLASS 加载 spring 上下文?

【问题讨论】:

  • 我也想知道这个,因为我也有类似的问题

标签: java spring junit spring-boot


【解决方案1】:

这里的解决方案是将DependencyInjectionTestExecutionListener 添加到您的@TestExecutionListeners 列表中,这将为依赖注入提供支持。

TestExecutionListener 提供对依赖注入的支持 和测试实例的初始化。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes ={ServerConfig.class,ServerThroughAMQPBrokerRabbitMQIntegrationTestConfig.class})
@Category({IntegrationTest.class})
@TestPropertySource("classpath:test.properties")
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@TestExecutionListeners(listeners = {DirtiesContextBeforeModesTestExecutionListener.class, DirtiesContextTestExecutionListener.class, DependencyInjectionTestExecutionListener.class})
public class ServerThroughAMQPBrokerRabbitMQIntegrationTest {

这是来自 DirtiesContextBeforeModesTestExecutionListener javadoc

当将 TestExecutionListeners 与默认值合并时,此侦听器 将自动在之前订购 DependencyInjectionTestExecutionListener;否则,这个监听器 必须手动配置为执行之前 DependencyInjectionTestExecutionListener。

您还可以删除测试类上的 @TestExecutionListeners 注释。如果不存在这样的注释,Spring 将注入默认侦听器,其中包括 DirtiesContextBeforeModesTestExecutionListener.classDirtiesContextTestExecutionListener.class

这里是 SpringBoot 应用没有@TestExecutionListeners 注解的默认监听器列表

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2017-11-29
    • 2017-10-09
    • 1970-01-01
    相关资源
    最近更新 更多