你好,我最近更新了我的 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.class
和 DirtiesContextTestExecutionListener.class
这是SpringBoot应用程序没有@TestExecutionListeners
注解的默认监听器列表
关于java - 使用@DirtiesContext BEFORE_CLASS 进行 Spring 启动测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33993942/