Video in progress

Strong Middle 🧪 Testing

When is @DirtiesContext really needed, and what does using it a lot cost?

When a test corrupts state inside the test context (a cache in a singleton bean, a scheduler, static configuration) in a way that can't be undone. Each time it's used, the context is evicted from the cache and the next test starts it from scratch.

📖 Answer

@DirtiesContext tells Spring "this context is dirty now, close it". The next test gets a new context even if it has the same configuration.

There are few cases where it's truly needed:

  • the test changes an in-memory cache or a counter inside a bean and there's no way to clean it;
  • the state of an embedded server or broker changes (for example, a topic is deleted);
  • the test adds a property to the Environment at runtime.

In many teams it's added to "fix a flaky test": a test fails after another one, someone puts @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) on it, and the test passes. The result is an extra 5-8 seconds per method. On one project, removing 40 of these annotations took CI from 14 minutes down to 6.

What to try before it:

@AfterEach
void cleanUp() {
    cacheManager.getCacheNames()
        .forEach(n -> cacheManager.getCache(n).clear());
    orderRepository.deleteAll();
}

In other words, clean the state yourself. If you can't clean it, then there's a problem in the bean's design (for example, a static field), and you should fix the code, not the test.