问题
I have an integration test class annotated as follows
@WebAppConfiguration
@ContextConfiguration(classes = {AppConfiguration.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class CacheConsumerTest {
}
Here's my AppConfiguration
@Configuration
@ComponentScan(basePackages = {"com.etc.etc.etc."})
@EnableWebMvc
public class AppConfiguration {
}
For some reason, none of my @Component
beans' @PreDestroy
is getting called at the end of all tests in CacheConsumerTest
. @PostConstruct
is however being called at the start, before any tests are run.
Anyone know what the problem may be? Some of my @Component
are background threads that I would like to have shut off (by having its @Predestroy called), otherwise the work they do in the background will cause subsequent tests in other test classes to fail.
I've tried adding @DirtiesContext(classMode=ClassMode.AFTER_CLASS)
but it didn't help.
EDIT: Figured out the problem, I had to do an additional step to make DirtiesContext work: Does Spring @DirtiesContext reload Spring context?
回答1:
SpringJUnit4ClassRunner
has a feature: it caches all started contexts and destroys them only at the end of running of all test cases. The reason is that often starting of new spring context may take several seconds that significantly increases the time needed for whole suite.
So, if you really need this you probably should extend SpringJUnit4ClassRunner
and make it not to cache the contexts. I guess that probably this runner already has such feature but unfortunately I cannot check this right now. Try to examine its code. It is not so complicated and probably you will find the solution quickly.
EDIT:
Just annotated your test case with @DirtiesContext
. Take a look here for details.
来源:https://stackoverflow.com/questions/22773116/spring-why-is-predestroy-not-called-at-end-of-each-test-class