Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Why is @PreDestroy not called at end of each test class?

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?

like image 750
Popcorn Avatar asked Mar 31 '14 22:03

Popcorn


1 Answers

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.

like image 197
AlexR Avatar answered Sep 27 '22 20:09

AlexR