Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 949
Jens Schauder Avatar asked Jan 11 '13 10:01

Jens Schauder


People also ask

How do I refresh application context in Spring boot?

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.

What does SpringBootTest annotation do?

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.


1 Answers

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 {    .. } 
like image 137
Johan Avatar answered Jan 04 '23 00:01

Johan