Skip to content

Commit 93f403c

Browse files
committed
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
1 parent d66d160 commit 93f403c

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import java.lang.reflect.Method;
2020

2121
import org.springframework.context.ApplicationContext;
22+
import org.springframework.context.ConfigurableApplicationContext;
2223
import org.springframework.core.AttributeAccessorSupport;
2324
import org.springframework.core.style.ToStringCreator;
2425
import org.springframework.test.annotation.DirtiesContext.HierarchyMode;
@@ -75,9 +76,18 @@ public DefaultTestContext(Class<?> testClass, MergedContextConfiguration mergedC
7576
* <p>The default implementation delegates to the {@link CacheAwareContextLoaderDelegate}
7677
* that was supplied when this {@code TestContext} was constructed.
7778
* @see CacheAwareContextLoaderDelegate#loadContext
79+
* @throws IllegalStateException if the context returned by the context
80+
* loader delegate is not <em>active</em> (i.e., has been closed).
7881
*/
7982
public ApplicationContext getApplicationContext() {
80-
return this.cacheAwareContextLoaderDelegate.loadContext(this.mergedContextConfiguration);
83+
ApplicationContext context = this.cacheAwareContextLoaderDelegate.loadContext(this.mergedContextConfiguration);
84+
if (context instanceof ConfigurableApplicationContext) {
85+
@SuppressWarnings("resource")
86+
ConfigurableApplicationContext cac = (ConfigurableApplicationContext) context;
87+
Assert.state(cac.isActive(), "The ApplicationContext loaded for [" + mergedContextConfiguration
88+
+ "] is not active. Ensure that the context has not been closed programmatically.");
89+
}
90+
return context;
8191
}
8292

8393
/**

0 commit comments

Comments
 (0)