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

标签 java spring junit spring-boot

你好,我最近更新了我的 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/

相关文章:

java - AssertJ 断言抛出异常或结果

java - Mockito:如何验证模拟是否是最后一次调用的模拟?

java - 打印数组列表元素问题

java - 为什么我的 libgdx 游戏速度逐渐变慢?

java - Spring Security SAML - 使用什么类型的SecurityContextRepository,如何注册

java - 我应该把 JUnit 测试放在哪里?

java - 为什么在 ActionBarActivity 上运行测试时会出现 NoClassDefFoundError?

java - 在 Java 中生成 N 个引用副本的只读列表的一行代码

java - Cors 过滤器 - 允许所有子域

java - 添加更多 Controller 时,Spring mvc 性能显着下降