Skip to content

Commit 29d307e

Browse files
committed
Clear ApplicationContext cache after a test class completes if necessary
The ApplicationContext has a resource cache that it uses while the context is being refreshed. Once the refresh phase completes, the cache is cleared as its content is no longer in use. If beans are lazily initialized, there is a case where the cache might be filled again as processing is deferred past the refresh phase. For those cases, the cache is not cleared. This can be a problem when running in this mode with a large set of test configurations as the TCF caches the related contexts. This commit includes an additional TestExecutionListener to the TCF that clears the resource cache if necessary once a test class completes. It is ordered so that it runs after `@DirtiesContext` support as marking the context as dirty will remove it from the cache and make that extra step unnecessary. Closes gh-30954
1 parent 4c77350 commit 29d307e

File tree

6 files changed

+209
-0
lines changed

6 files changed

+209
-0
lines changed

framework-docs/modules/ROOT/pages/testing/testcontext-framework/tel-config.adoc

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ by default, exactly in the following order:
1616
Micrometer's `ObservationRegistry`.
1717
* `DirtiesContextTestExecutionListener`: Handles the `@DirtiesContext` annotation for
1818
"`after`" modes.
19+
* `CommonCacheTestExecutionListener`: Clears application context cache if necessary.
1920
* `TransactionalTestExecutionListener`: Provides transactional test execution with
2021
default rollback semantics.
2122
* `SqlScriptsTestExecutionListener`: Runs SQL scripts configured by using the `@Sql`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
* Copyright 2002-2024 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.test.context.support;
18+
19+
import org.springframework.context.ApplicationContext;
20+
import org.springframework.context.support.AbstractApplicationContext;
21+
import org.springframework.test.context.TestContext;
22+
23+
/**
24+
* {@code TestExecutionListener} which makes sure that caches are cleared once
25+
* they are no longer required. Clears the resource cache of the
26+
* {@link ApplicationContext} as it is only required during the beans
27+
* initialization phase. Runs after {@link DirtiesContextTestExecutionListener}
28+
* as dirtying the context will remove it from the cache and make this
29+
* unnecessary.
30+
*
31+
* @author Stephane Nicoll
32+
* @since 6.2
33+
*/
34+
public class CommonCacheTestExecutionListener extends AbstractTestExecutionListener {
35+
36+
/**
37+
* Returns {@code 3005}.
38+
*/
39+
@Override
40+
public final int getOrder() {
41+
return 3005;
42+
}
43+
44+
45+
@Override
46+
public void afterTestClass(TestContext testContext) throws Exception {
47+
if (testContext.hasApplicationContext()) {
48+
ApplicationContext applicationContext = testContext.getApplicationContext();
49+
if (applicationContext instanceof AbstractApplicationContext ctx) {
50+
ctx.clearResourceCaches();
51+
}
52+
}
53+
}
54+
55+
}

spring-test/src/main/resources/META-INF/spring.factories

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ org.springframework.test.context.TestExecutionListener = \
66
org.springframework.test.context.event.ApplicationEventsTestExecutionListener,\
77
org.springframework.test.context.bean.override.mockito.MockitoTestExecutionListener,\
88
org.springframework.test.context.support.DependencyInjectionTestExecutionListener,\
9+
org.springframework.test.context.support.CommonCacheTestExecutionListener,\
910
org.springframework.test.context.observation.MicrometerObservationRegistryTestExecutionListener,\
1011
org.springframework.test.context.support.DirtiesContextTestExecutionListener,\
1112
org.springframework.test.context.transaction.TransactionalTestExecutionListener,\

spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java

+5
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import org.springframework.test.context.event.EventPublishingTestExecutionListener;
3333
import org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener;
3434
import org.springframework.test.context.support.AbstractTestExecutionListener;
35+
import org.springframework.test.context.support.CommonCacheTestExecutionListener;
3536
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
3637
import org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener;
3738
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
@@ -72,6 +73,7 @@ void defaultListeners() {
7273
DependencyInjectionTestExecutionListener.class,//
7374
micrometerListenerClass,//
7475
DirtiesContextTestExecutionListener.class,//
76+
CommonCacheTestExecutionListener.class, //
7577
TransactionalTestExecutionListener.class,//
7678
SqlScriptsTestExecutionListener.class,//
7779
EventPublishingTestExecutionListener.class,//
@@ -94,6 +96,7 @@ void defaultListenersMergedWithCustomListenerPrepended() {
9496
DependencyInjectionTestExecutionListener.class,//
9597
micrometerListenerClass,//
9698
DirtiesContextTestExecutionListener.class,//
99+
CommonCacheTestExecutionListener.class, //
97100
TransactionalTestExecutionListener.class,//
98101
SqlScriptsTestExecutionListener.class,//
99102
EventPublishingTestExecutionListener.class,//
@@ -115,6 +118,7 @@ void defaultListenersMergedWithCustomListenerAppended() {
115118
DependencyInjectionTestExecutionListener.class,//
116119
micrometerListenerClass,//
117120
DirtiesContextTestExecutionListener.class,//
121+
CommonCacheTestExecutionListener.class, //
118122
TransactionalTestExecutionListener.class,
119123
SqlScriptsTestExecutionListener.class,//
120124
EventPublishingTestExecutionListener.class,//
@@ -138,6 +142,7 @@ void defaultListenersMergedWithCustomListenerInserted() {
138142
BarTestExecutionListener.class,//
139143
micrometerListenerClass,//
140144
DirtiesContextTestExecutionListener.class,//
145+
CommonCacheTestExecutionListener.class, //
141146
TransactionalTestExecutionListener.class,//
142147
SqlScriptsTestExecutionListener.class,//
143148
EventPublishingTestExecutionListener.class,//
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
* Copyright 2002-2024 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.test.context.cache;
18+
19+
import org.junit.jupiter.api.ClassOrderer;
20+
import org.junit.jupiter.api.Nested;
21+
import org.junit.jupiter.api.Order;
22+
import org.junit.jupiter.api.Test;
23+
import org.junit.jupiter.api.TestClassOrder;
24+
25+
import org.springframework.beans.factory.annotation.Autowired;
26+
import org.springframework.context.annotation.Bean;
27+
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
28+
import org.springframework.context.annotation.Configuration;
29+
import org.springframework.context.annotation.Lazy;
30+
import org.springframework.context.support.AbstractApplicationContext;
31+
import org.springframework.core.io.ResourceLoader;
32+
import org.springframework.core.type.classreading.MetadataReader;
33+
import org.springframework.test.context.cache.SpringExtensionCommonCacheTests.TestConfiguration;
34+
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
35+
36+
import static org.assertj.core.api.Assertions.assertThat;
37+
38+
/**
39+
* Tests that verify that common caches are cleared at the end of a test
40+
* class. Regular callback cannot be used to validate this as they run
41+
* before the listener, so we need two test classes that are ordered to
42+
* validate the result.
43+
*
44+
* @author Stephane Nicoll
45+
*/
46+
@SpringJUnitConfig(classes = TestConfiguration.class)
47+
@TestClassOrder(ClassOrderer.OrderAnnotation.class)
48+
class SpringExtensionCommonCacheTests {
49+
50+
@Autowired
51+
AbstractApplicationContext applicationContext;
52+
53+
@Nested
54+
@Order(1)
55+
class FirstTests {
56+
57+
@Test
58+
void lazyInitBeans() {
59+
applicationContext.getBean(String.class);
60+
assertThat(applicationContext.getResourceCache(MetadataReader.class)).isNotEmpty();
61+
}
62+
63+
}
64+
65+
@Nested
66+
@Order(2)
67+
class SecondTests {
68+
69+
@Test
70+
void validateCommonCacheIsCleared() {
71+
assertThat(applicationContext.getResourceCache(MetadataReader.class)).isEmpty();
72+
}
73+
74+
}
75+
76+
77+
@Configuration
78+
static class TestConfiguration {
79+
80+
@Bean
81+
@Lazy
82+
String dummyBean(ResourceLoader resourceLoader) {
83+
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
84+
scanner.setResourceLoader(resourceLoader);
85+
scanner.findCandidateComponents(TestConfiguration.class.getPackageName());
86+
return "Dummy";
87+
}
88+
}
89+
90+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
* Copyright 2002-2024 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.test.context.support;
18+
19+
import org.junit.jupiter.api.Test;
20+
21+
import org.springframework.context.support.AbstractApplicationContext;
22+
import org.springframework.test.context.TestContext;
23+
24+
import static org.mockito.BDDMockito.given;
25+
import static org.mockito.Mockito.mock;
26+
import static org.mockito.Mockito.verify;
27+
import static org.mockito.Mockito.verifyNoMoreInteractions;
28+
29+
/**
30+
* Tests for {@link CommonCacheTestExecutionListener}.
31+
*
32+
* @author Stephane Nicoll
33+
*/
34+
class CommonCacheTestExecutionListenerTests {
35+
36+
private final CommonCacheTestExecutionListener listener = new CommonCacheTestExecutionListener();
37+
38+
@Test
39+
void afterTestClassWhenContextIsAvailable() throws Exception {
40+
AbstractApplicationContext applicationContext = mock(AbstractApplicationContext.class);
41+
TestContext testContext = mock(TestContext.class);
42+
given(testContext.hasApplicationContext()).willReturn(true);
43+
given(testContext.getApplicationContext()).willReturn(applicationContext);
44+
listener.afterTestClass(testContext);
45+
verify(applicationContext).clearResourceCaches();
46+
}
47+
48+
@Test
49+
void afterTestClassCWhenContextIsNotAvailable() throws Exception {
50+
TestContext testContext = mock(TestContext.class);
51+
given(testContext.hasApplicationContext()).willReturn(false);
52+
listener.afterTestClass(testContext);
53+
verify(testContext).hasApplicationContext();
54+
verifyNoMoreInteractions(testContext);
55+
}
56+
57+
}

0 commit comments

Comments
 (0)