-
Notifications
You must be signed in to change notification settings - Fork 41.2k
spring-boot-testcontainers when used on abstract class creates multiple contexts #42854
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Hey, @wyhasany Thank you very much for your sample. Your tests fail because The issue is that How can you fix this? Option 1 @SpringBootTest
@ImportTestcontainers
//@Testcontainers also could be used if needed, but you can't annotate the container with @Container annotation
abstract class DemoApplicationTests {
@ServiceConnection
static MongoDBContainer mongoDbContainer = new MongoDBContainer(DockerImageName.parse("mongo:latest"));
// ...
} Option 2 @SpringBootTest
@Import(TestcontainersConfiguration.class)
abstract class DemoApplicationTests {
}
@TestConfiguration(proxyBeanMethods = false)
class TestcontainersConfiguration {
@Bean
@ServiceConnection
MongoDBContainer mongoDbContainer() {
return new MongoDBContainer(DockerImageName.parse("mongo:latest"));
}
}
|
I don't think that's the case. Only one context is created due to the test context Framework's caching as each test class has identical configuration.
As @nosan has explained above, it's This is a duplicate of #38237. In addition to @nosan's suggestions, you can also avoid the problem by applying |
@wilkinsona you're correct. I was confused by seeing the Spring banner twice.
I would prefer to avoid recommending Would you mind if I submitted a PR to include information to docs about avoiding the use of |
Thanks for the offer of a PR. I've added a note to #35236 as there are some other lifecycle issues to consider and I think it may be better to document them as a whole. |
Creating integration tests with a shared abstract class to avoid initializing multiple contexts does not work as expected when a container is managed by Spring:
When running these tests, two application contexts are created, causing the container to be restarted. The second test then tries to connect to the container, which was already stopped after the first test.
To reproduce the issue, run the following command on the attached project:
./gradlew test
You can find the sample project here: demo.zip
Let me know if you'd like any further clarifications.
The text was updated successfully, but these errors were encountered: