How to force a fresh version of the Spring context

2019-04-18 13:28发布

问题:

I use the SpringJUnit4ClassRunner for writing integration tests. I also use @DirtiesContext for tests that leave the context in an broken state behind and that works just fine.

But now I have a test the sets an important SystemProperty in an static initializer, which in turn is used in the Spring context. This again works fine when the test executes on its own. But when I run the test with other tests the Spring context gets already created with out that property set and gets reused by my new Test.

How can I force the fresh creation of a Spring context in my test, which then will use the changed System Property?

回答1:

As of Spring 4.2 the DirtiesContext annotation supports the following new phases: BEFORE_CLASS, BEFORE_EACH_TEST_METHOD and BEFORE_METHOD. So you can now do for example:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(...)
@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
public class MyTest {
   ..
}


回答2:

Pre-Spring 4.2:

I can only suggest a hack unfortunately - you are right, there does not seem to be a simple way to initialize a new application context rather than using a cached application context. These are some of the workarounds that I can suggest:

  1. Use a slightly different @ContextConfiguration - a quick and dirty way to do that could be to add an @ActiveProfiles annotation to the test class, this way Spring will be forced to cache the context with a new key OR define a dummy context with your existing configuration as imports

  2. A hack, but JUnit 4.11+ allows some level of control over test method ordering, it is possible to have a test method right before your target test method and have the dummy test method annotated with @DirtiesContext, this way when your target method is called a fresh context will be created.



回答3:

There are several options:

  1. You can create an individual spring context for this test by loading another configuration into it. That way, your test will be completely independent of every other test.
  2. You can create a stripped down configuration for this test. That would achieve the same but be faster.
  3. Create a test suite which runs this test first.


标签: spring junit4