问题
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