@@ -2947,3 +2947,48 @@ The following example shows how to do so in Gradle:
2947
2947
// ...
2948
2948
}
2949
2949
----
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