Spring boot test with @DirtiesContext BEFORE_CLASS

社会主义新天地 提交于 2019-12-23 13:02:26

问题


Hello I recently updated my spring boot application and noticed new feature ( DirtiesContext.ClassMode.BEFORE_CLASS), that seems fit my needs, because I had the problem with reloading bean with method annotated @RabbitListener, for some reason Spring reloaded that bean, but old bean was using as rabbit listener. (See here)

My code:

@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 {

The issue that,after adding DirtiesContext.ClassMode.BEFORE_CLASS Spring stops loading beans from:

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

So the questions:

How should I load spring context with DirtiesContext.ClassMode.BEFORE_CLASS ?


回答1:


The solution here is to add DependencyInjectionTestExecutionListener to list of your @TestExecutionListeners, which will provide support for dependency injection.

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 {

This is from 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.

Also you could remove @TestExecutionListeners annotation on your test class. If no such annotation is present Spring will inject the default listener which will include DirtiesContextBeforeModesTestExecutionListener.class and DirtiesContextTestExecutionListener.class

Here is the list of default listeners without @TestExecutionListeners annotation for SpringBoot application



来源:https://stackoverflow.com/questions/33993942/spring-boot-test-with-dirtiescontext-before-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!