jpprade
jpprade

Reputation: 3684

Should I use @DirtiesContext on every class?

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 test classes to be independent. I was assuming that it was the default behavior, but when I run all the tests 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 ?

Upvotes: 28

Views: 30502

Answers (1)

geoand
geoand

Reputation: 64099

Spring caches the application context by default when running tests. The key that Spring uses for the cache is made of the following:

  • locations (from @ContextConfiguration)
  • classes (from @ContextConfiguration)
  • contextInitializerClasses (from @ContextConfiguration)
  • contextLoader (from @ContextConfiguration)
  • activeProfiles (from @ActiveProfiles)
  • resourceBasePath (from @WebAppConfiguration)

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.

Upvotes: 41

Related Questions