David Kubecka
David Kubecka

Reputation: 300

Start-up hook in testcontainers and Spring Boot 3.1

We would like to utilize the enhanced Testcontainers support in Spring Boot 3.1 As a consequence, the Spring itself is now responsible for starting the containers, whereas previously we had full control over the start-up, and we utilized that to run some hooks once the containers were started (e.g. creating a DB in PostgreSQL). Given that Spring is now in control of the containers starting how to perform a custom start-up operation so that it's run only once the container is fully started and ready?

I'm talking specifically about this way of declaring the container

@TestConfiguration(proxyBeanMethods = false)
public class MyContainersConfiguration {

    @Bean
    @ServiceConnection
    public Neo4jContainer<?> neo4jContainer() {
        return new Neo4jContainer<>("neo4j:5").withReuse(true);
    }

}

Here Spring is in the control of the full lifecycle of the container, that is just a start-up in this case as the shutdown is to be performed manually (withReuse(true)).

I should add that Spring being in control of the start-up is a feature. Previously, because there was no @ServiceConnection, one had to have a direct container holder in order to extract the dynamic connection info from it put it into app properties. This is no longer needed with the new features but at the same time one loses the access to the underlying container, especially one seems to be no longer able to perform a start-up action.

Also, because the container might be started only once per multiple tests (due to Spring context reuse) I cannot simply perform my container start-up actions in BeforeAll or the like but I really want to run them once on container start-up.

Upvotes: 2

Views: 552

Answers (1)

Kartik
Kartik

Reputation: 7917

Since I see no other answers, let me post a hacky way of how I did it using @DynamicPropertySource:

@JvmStatic
@DynamicPropertySource
fun properties(registry: DynamicPropertyRegistry) {
    // set properties
    registry.add("spring.cloud.aws.region.static") { localStackContainer.region }
    registry.add("spring.cloud.aws.endpoint") { localStackContainer.endpoint.toString() }

    // kind of startup hook
    onContainerStarted()
}

private fun onContainerStarted() {
    // do something here
}

Upvotes: 1

Related Questions