How to force a fresh version of the Spring context BEFORE the test executes

前端 未结 3 1344
有刺的猬
有刺的猬 2021-02-18 15:54

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

相关标签:
3条回答
  • 2021-02-18 16:36

    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 {
       ..
    }
    
    0 讨论(0)
  • 2021-02-18 16:38

    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.
    0 讨论(0)
  • 2021-02-18 16:44

    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.

    0 讨论(0)
提交回复
热议问题