I have the following piece of code for my abstract test class (I know XmlBeanFactory with ClassPathResource is deprecated, but it’s unlikely to be the case of the problem).
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public abstract class AbstractIntegrationTest {
/** Spring context. */
protected static final BeanFactory context = new XmlBeanFactory(new ClassPathResource(
"com/.../AbstractIntegrationTest-context.xml"));
...
}
It loads the default test configuration XML file AbstractIntegrationTest-context.xml (and then I use autowiring). I also need to use Spring in static methods annotated with @BeforeClass and @AfterClass, so I have a separate context variable pointing to the same location. But the thing is that this is a separate context, which will have different instances of beans. So how can I merge these contexts or how can I invoke Spring’s bean initialization defined by @ContextConfiguration from my static context?
I have in mind a possible solution by getting rid of those static members, but I’m curious, if I can do it with relatively small changes to the code.
You are right, your code will produce two application contexts: one will be started, cached and maintained for you by
@ContextConfigurationannotation. The second context you create yourself. It doesn’t make much sense to have both.Unfortunately JUnit is not very well suited for integration tests – mainly because you cannot have before class and after class non-static methods. I see two choices for you:
switch to testng – I know it’s a big step
encode your setup/tear down logic in a Spring bean included in the context only during tests – but then it will run only once, before all tests.
There are also less elegant approaches. You can use
staticvariable and inject context to it:Or you can annotate your test class with
@DirtiesContextand do the cleanup in some test bean: