From 93f403cbf65ff4d584dc2d168c929d5683e065a4 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Mon, 20 Apr 2015 00:37:16 +0200 Subject: [PATCH] Ensure that contexts loaded by the TCF are active This commit adds an assertion to DefaultTestContext's getApplicationContext() method to ensure that a context loaded by the Spring TestContext Framework (TCF) or retrieved from the ContextCache is still active. This extra check helps to avoid situations where developers manually close a cached context instead of relying on the @DirtiesContext support. Issue: SPR-12932 --- .../test/context/support/DefaultTestContext.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java b/spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java index bd730b3254..38dac51521 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java @@ -19,6 +19,7 @@ package org.springframework.test.context.support; import java.lang.reflect.Method; import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.AttributeAccessorSupport; import org.springframework.core.style.ToStringCreator; import org.springframework.test.annotation.DirtiesContext.HierarchyMode; @@ -75,9 +76,18 @@ public class DefaultTestContext extends AttributeAccessorSupport implements Test *

The default implementation delegates to the {@link CacheAwareContextLoaderDelegate} * that was supplied when this {@code TestContext} was constructed. * @see CacheAwareContextLoaderDelegate#loadContext + * @throws IllegalStateException if the context returned by the context + * loader delegate is not active (i.e., has been closed). */ public ApplicationContext getApplicationContext() { - return this.cacheAwareContextLoaderDelegate.loadContext(this.mergedContextConfiguration); + ApplicationContext context = this.cacheAwareContextLoaderDelegate.loadContext(this.mergedContextConfiguration); + if (context instanceof ConfigurableApplicationContext) { + @SuppressWarnings("resource") + ConfigurableApplicationContext cac = (ConfigurableApplicationContext) context; + Assert.state(cac.isActive(), "The ApplicationContext loaded for [" + mergedContextConfiguration + + "] is not active. Ensure that the context has not been closed programmatically."); + } + return context; } /**