From 3e3ff26129798b6523b48829dff035b78e529df8 Mon Sep 17 00:00:00 2001 From: Madhura Bhave Date: Mon, 11 May 2020 19:07:47 -0700 Subject: [PATCH] Add a testcontainers section in the reference docs Closes gh-20734 --- .../src/docs/asciidoc/howto.adoc | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto.adoc index d740c0c026..f5611becfe 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto.adoc @@ -2947,3 +2947,48 @@ The following example shows how to do so in Gradle: // ... } ---- + + + +[[howto-testcontainers]] +=== Use TestContainers for integration testing +The https://www.testcontainers.org/[TestContainers] library provides a way to manage services running inside Docker containers. +It integrates with JUnit, allowing you to write a test class that can start up a container before any of the tests run. +TestContainers is especially useful for writing integration tests that talk to a real backend service such as MySQL, MongoDB, Cassandra etc. +TestContainers can be used in a Spring Boot test as follows: + +[source,java,indent=0,subs="verbatim,quotes,attributes"] +---- +@SpringBootTest +@Testcontainers +class ExampleIntegrationTests { + + @Container + static Neo4jContainer neo4j = new Neo4jContainer<>(); + +} +---- + +This will start up a docker container running Neo4j (if Docker is running locally) before any of the tests are run. +In most cases, you will need to configure the application using details from the running container, such as container IP or port. + +This can be done with a static `@DynamicPropertySource` method that allows adding adding dynamic property values to the Spring Environment. + +[source,java,indent=0,subs="verbatim,quotes,attributes"] +---- +@SpringBootTest +@Testcontainers +class ExampleIntegrationTests { + + @Container + static Neo4jContainer neo4j = new Neo4jContainer<>(); + + @DynamicPropertySource + static void neo4jProperties(DynamicPropertyRegistry registry) { + registry.add("spring.data.neo4j.uri", neo4j::getBoltUrl); + } + +} +---- + +The above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container.