Mismatched DirtiesContext Mode

ID

java.appropriate_dirtiescontext_modes

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

reliability, testing

Description

Reports a Spring @DirtiesContext annotation whose methodMode attribute is set on a type, or whose classMode attribute is set on a method.

Rationale

Spring only reads methodMode from a @DirtiesContext placed on a method, and classMode from one placed on a type. Setting the attribute that belongs to the other scope has no effect at all: the context is not reset the way the annotation appears to configure, and the mistake is easy to miss because the annotation still compiles and still runs.

@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) // has no effect on a type
class CacheResetTests {

  @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) // has no effect on a method
  void resetsCache() {
  }
}

Remediation

Use classMode on the type and methodMode on the method.

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class CacheResetTests {

  @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
  void resetsCache() {
  }
}

What is not reported

hierarchyMode alone, or a @DirtiesContext with no mode attribute at all, is scope-agnostic and never flagged. A composed annotation built on top of @DirtiesContext (a custom meta-annotation) is not traced: telling what such a custom annotation ultimately targets would need to follow its own usages, which this rule does not attempt.

© 2026 Xygeni. All rights reserved