Uploaded image for project: 'Spring Framework'
  1. Spring Framework
  2. SPR-17654

Document effect of @DirtiesContext when used with constructor injection

    XMLWordPrintable

    Details

    • Type: Task
    • Status: Resolved
    • Priority: Minor
    • Resolution: Complete
    • Affects Version/s: 5.0.12
    • Fix Version/s: 5.1.5, 5.2 RC1
    • Component/s: [Documentation], Test
    • Labels:
      None
    • Last commented by a User:
      true

      Description

      Overview

      A recent discussion in the #spring channel on Kotlin Slack pointed out that issues arise when using @DirtiesContext to evict an ApplicationContext from the cache between test methods if the test class is executed with JUnit Jupiter and @TestInstance(PER_CLASS) semantics.

      Analysis

      Constructor injection for Spring-managed components will not work properly if @DirtiesContext is used to evict the test's ApplicationContext before or after test methods.

      The reason is that the test instance will retain references to beans that came from a (now) closed ApplicationContext, and dependency injection will not occur again (to reset the references) since the constructor will only be invoked once.

      To use @DirtiesContext before or after methods, one must allow dependencies from Spring to be injected via fields or setter/configuration methods.

      Deliverables

      • Document this in the Testing chapter of the reference manual

        Attachments

          Activity

            People

            Assignee:
            sbrannen Sam Brannen
            Reporter:
            sbrannen Sam Brannen
            Last updater:
            Spring Issues Spring Issues
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved:
              Days since last comment:
              3 years, 29 weeks, 6 days ago