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?
For a Spring Boot Actuator application, some additional management endpoints are available. You can use: POST to /actuator/env to update the Environment and rebind @ConfigurationProperties and log levels. /actuator/refresh to re-load the boot strap context and refresh the @RefreshScope beans.
The @SpringBootTest annotation loads the complete Spring application context. In contrast, a test slice annotation only loads beans required to test a particular layer. And because of this, we can avoid unnecessary mocking and side effects.
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 { .. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With