gpt4 book ai didi

java - 使用@DirtiesContext BEFORE_CLASS 进行 Spring 启动测试

转载 作者:搜寻专家 更新时间:2023-11-01 02:23:02 25 4
gpt4 key购买 nike

你好,我最近更新了我的 spring boot 应用程序并注意到了新功能(DirtiesContext.ClassMode.BEFORE_CLASS),这似乎符合我的需要,因为我在使用注释为@RabbitListener 的方法重新加载 bean 时遇到了问题,出于某种原因 Spring 重新加载了那个 bean ,但是老 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 上下文?

最佳答案

这里的解决办法是加上DependencyInjectionTestExecutionListener列出您的 @TestExecutionListeners,这将为依赖注入(inject)提供支持。

TestExecutionListener which provides support for dependency injection and initialization of test instances.

@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

When merging TestExecutionListeners with the defaults, this listener will automatically be ordered before the DependencyInjectionTestExecutionListener; otherwise, this listener must be manually configured to execute before the DependencyInjectionTestExecutionListener.

您还可以删除测试类上的 @TestExecutionListeners 注释。如果没有这样的注解,Spring 将注入(inject)默认监听器,其中包括 DirtiesContextBeforeModesTestExecutionListener.classDirtiesContextTestExecutionListener.class

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

enter image description here

关于java - 使用@DirtiesContext BEFORE_CLASS 进行 Spring 启动测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33993942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com