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

前端 未结 3 1342
有刺的猬
有刺的猬 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: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.

提交回复
热议问题