27

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

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
jpprade
  • 3,497
  • 3
  • 45
  • 58

1 Answers1

39

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.

geoand
  • 60,071
  • 24
  • 172
  • 190
  • 2
    I have a reverse problem, I am not using Dirties anything, but my spring context gets created for each test, what am i doing wrong? – Kalpesh Soni Oct 12 '16 at 19:19
  • @KalpeshSoni I can't really say without more info – geoand Oct 13 '16 at 12:28
  • The pattern we have is , we have a base class with @RunWith(SpringRunner) and @SpringBootTest etc, and all my tests extend this, so that it uses exact same config, but looks like this polymorphism - spring tests dont like it to cache the context? – Kalpesh Soni Apr 05 '18 at 18:52
  • Is it used to clear spring context cache while executing tests? Pls confirm. – Akash5288 Dec 23 '18 at 07:09
  • What do you mean by Spring Context Cache? – geoand Jan 02 '19 at 10:10