+-
java – 使用@DirtiesContext BEFORE_CLASS进行Spring启动测试
您好我最近更新了我的 spring启动应用程序并注意到了新功能(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上下文?

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

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将注入默认监听器,其中包括DirtiesContextBeforeModesTestExecutionListener.class和DirtiesContextTestExecutionListener.class

以下是没有SpringBoot应用程序的@TestExecutionListeners注释的默认侦听器列表

enter image description here

点击查看更多相关文章

转载注明原文:java – 使用@DirtiesContext BEFORE_CLASS进行Spring启动测试 - 乐贴网