Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.Sign up
@PreDestroy method in test instance not executed when run with SpringJUnit4ClassRunner [SPR-4868] #9544
I have a JUnit 4 class that is being run with the SpringJUnit4ClassRunner. I have two methods annotated with the
Referenced from: commits e71cd06
2 votes, 4 watchers
Juergen Hoeller commented
Note that the Spring ApplicationContexts managed by SpringJUnit4ClassRunner are shared between all tests with the same context key... So destruction methods could only run after all related tests have executed.
However, there is no corresponding callback in JUnit... This has been reported before in the context of Ant's JUnit runner (#6700). We might be unable to do something about this without extensions to JUnit... In any case, we'll revisit the topic for Spring 3.0.
Sam Brannen commented
It's fine to use
In your particular case, you should use JUnit's
I think this will provide you the behavior you're looking for.
Please also see the related discussions in #12035.
Sam Brannen commented
To follow up on my previous comment, the reference manual has been updated for Spring 3.2 to include the following note in the Testing chapter.
<note> <title>JSR-250 Lifecycle Annotations</title> <para>In the Spring TestContext Framework <interfacename>@PostConstruct</interfacename> and <interfacename>@PreDestroy</interfacename> may be used with standard semantics on any application components configured in the <interfacename>ApplicationContext</interfacename>; however, these lifecycle annotations have limited usage within an actual test class.</para> <para>If a method within a test class is annotated with <interfacename>@PostConstruct</interfacename>, that method will be executed before any <emphasis>before</emphasis> methods of the underlying test framework (e.g., methods annotated with JUnit's <interfacename>@Before</interfacename>), and that will apply for every test method in the test class. On the other hand, if a method within a test class is annotated with <interfacename>@PreDestroy</interfacename>, that method will <emphasis role="bold">never</emphasis> be executed. Within a test class it is therefore recommended to use test lifecycle callbacks from the underlying test framework instead of <interfacename>@PostConstruct</interfacename> and <interfacename>@PreDestroy</interfacename>.</para> </note>