Skip to content

Commit 3e3ff26

Browse files
committed
Add a testcontainers section in the reference docs
Closes gh-20734
1 parent 7468f57 commit 3e3ff26

File tree

1 file changed

+45
-0
lines changed
  • spring-boot-project/spring-boot-docs/src/docs/asciidoc

1 file changed

+45
-0
lines changed

spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto.adoc

+45
Original file line numberDiff line numberDiff line change
@@ -2947,3 +2947,48 @@ The following example shows how to do so in Gradle:
29472947
// ...
29482948
}
29492949
----
2950+
2951+
2952+
2953+
[[howto-testcontainers]]
2954+
=== Use TestContainers for integration testing
2955+
The https://www.testcontainers.org/[TestContainers] library provides a way to manage services running inside Docker containers.
2956+
It integrates with JUnit, allowing you to write a test class that can start up a container before any of the tests run.
2957+
TestContainers is especially useful for writing integration tests that talk to a real backend service such as MySQL, MongoDB, Cassandra etc.
2958+
TestContainers can be used in a Spring Boot test as follows:
2959+
2960+
[source,java,indent=0,subs="verbatim,quotes,attributes"]
2961+
----
2962+
@SpringBootTest
2963+
@Testcontainers
2964+
class ExampleIntegrationTests {
2965+
2966+
@Container
2967+
static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
2968+
2969+
}
2970+
----
2971+
2972+
This will start up a docker container running Neo4j (if Docker is running locally) before any of the tests are run.
2973+
In most cases, you will need to configure the application using details from the running container, such as container IP or port.
2974+
2975+
This can be done with a static `@DynamicPropertySource` method that allows adding adding dynamic property values to the Spring Environment.
2976+
2977+
[source,java,indent=0,subs="verbatim,quotes,attributes"]
2978+
----
2979+
@SpringBootTest
2980+
@Testcontainers
2981+
class ExampleIntegrationTests {
2982+
2983+
@Container
2984+
static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
2985+
2986+
@DynamicPropertySource
2987+
static void neo4jProperties(DynamicPropertyRegistry registry) {
2988+
registry.add("spring.data.neo4j.uri", neo4j::getBoltUrl);
2989+
}
2990+
2991+
}
2992+
----
2993+
2994+
The above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container.

0 commit comments

Comments
 (0)