I have several junit tests,
@ContextConfiguration(locations = { "file:../business/src/test/resources/application-context-test.xml", "file:src/main/webapp/WEB-INF/confA.xml", "classpath:/mvc-dispatcher-servlet-test.xml"}) @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) public class ProductContentControllerTest { ... }
Inside a class all tests have to run in the same context (which is the case).
But I want all my tests classes to be independent. I was assuming that it was the default behavior, but when I run all the test together, it seems to run too fast.
How does it work? Is the application context started only once for every test class ?
Should I add : @DirtiesContext(classMode= ClassMode.AFTER_CLASS)
on each test class ?
thanks
@DirtiesContext is a Spring testing annotation. It indicates the associated test or class modifies the ApplicationContext. It tells the testing framework to close and recreate the context for later tests. We can annotate a test method or an entire class.
@RunWith(SpringRunner. class) tells JUnit to run using Spring's testing support. SpringRunner is the new name for SpringJUnit4ClassRunner , it's just a bit easier on the eye.
Annotation Type ContextConfiguration. @ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.
The @SpringBootTest annotation is useful when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests. We can use the webEnvironment attribute of @SpringBootTest to configure our runtime environment; we're using WebEnvironment.
Spring caches the application context by default when running tests. The key that Spring uses for the cache is made of the following:
All the details of the caching can be found in the documentation.
In my experience, there is rarely a need to use @DirtiesContext
in order to force Spring to recreate the context. I haven't come across too many situations where it's needed - the only one that comes to mind easily is the use of a shared cache manager.
You are better using it only on tests that you absolutely positively need it. Execution speed will be far too slow if you use @DirtiesContext
on every test and you won't be getting anything in return.
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