Why is this an issue?

In a Spring application, the @DirtiesContext annotation marks the ApplicationContext as dirty and indicates that it should be cleared and recreated. This is important in tests that modify the context, such as altering the state of singleton beans or databases.

Misconfiguring @DirtiesContext by setting the methodMode at the class level or the classMode at the method level will make the annotation have no effect.

This rule will raise an issue when the incorrect mode is configured on a @DirtiesContext annotation targeting a different scope.

How to fix it

Code examples

Noncompliant code example

@ContextConfiguration
@DirtiesContext(methodMode = MethodMode.AFTER_METHOD) // Noncompliant, for class-level control, use classMode instead.
public class TestClass {
  @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) // Non compliant, for method-level control use methodMode instead
  public void test() {...}
}

Compliant solution

@ContextConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class TestClass {
  @DirtiesContext(methodMode = MethodMode.AFTER_METHOD)
  public void test() {...}
}

Resources

Documentation