Adding Testcontainers to a Spring Boot project
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's repository tests need a real MySQL 8.4, but nobody wants to install a database and reset it by hand before every run. How can a test start MySQL by itself and throw it away afterwards?
Dependencies from the Spring Boot BOM
A BOM, or bill of materials, is a list of tested library versions that a framework manages for you. Spring Boot's BOM lists Testcontainers, so its dependencies need no <version> in pom.xml.
Testcontainers needs three test dependencies. None has a <version>, because Spring Boot's dependency management already lists them.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-testcontainers</artifactId> <scope>test</scope></dependency><dependency> <groupId>org.testcontainers</groupId> <artifactId>testcontainers-junit-jupiter</artifactId> <scope>test</scope></dependency><dependency> <groupId>org.testcontainers</groupId> <artifactId>testcontainers-mysql</artifactId> <scope>test</scope></dependency>What each one does:
spring-boot-testcontainers: Spring Boot's integration, used from the next lesson on.testcontainers-junit-jupiter: the JUnit 5 extension behind@Testcontainersand@Container.testcontainers-mysql: theMySQLContainerclass.
Testcontainers 2 renamed its modules, and Boot 4.1.1 brings Testcontainers 2.0.x. Older tutorials use junit-jupiter, mysql and org.testcontainers.containers.MySQLContainer<>; in 2.x the class is org.testcontainers.mysql.MySQLContainer, without a type parameter.
Fix the error
Fix the dependency name
Maven cannot resolve the dependency. Pick the line that fixes it.
Round 1 of 2
A tutorial for Testcontainers 1.x was copied into ShopLite.
Error
[ERROR] 'dependencies.dependency.version' for org.testcontainers:junit-jupiter:jar is missing.
First test: @Testcontainers, @Container and @DynamicPropertySource
@DynamicPropertySource marks a static method in a test class that adds properties to Spring's environment from values computed at run time, such as a container's random JDBC URL. Spring reads them before it creates the DataSource.
This first test starts one MySQL container for the class and hands its URL, user and password to Spring. Flyway then builds ShopLite's tables inside it.
Example 1 · src/test/java/com/shoplite/product/ProductRepositoryMySqlIT.java
Runs in: the shoplite-api Spring Boot project with Docker running
package com.shoplite.product;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.jdbc.core.simple.JdbcClient;import org.springframework.test.context.DynamicPropertyRegistry;import org.springframework.test.context.DynamicPropertySource;import org.testcontainers.junit.jupiter.Container;import org.testcontainers.junit.jupiter.Testcontainers;import org.testcontainers.mysql.MySQLContainer;
@SpringBootTest@Testcontainersclass ProductRepositoryMySqlIT {
@Container static MySQLContainer mysql = new MySQLContainer("mysql:8.4"); // one container for the class
@DynamicPropertySource static void databaseProperties(DynamicPropertyRegistry registry) { registry.add("spring.datasource.url", mysql::getJdbcUrl); registry.add("spring.datasource.username", mysql::getUsername); registry.add("spring.datasource.password", mysql::getPassword); }
@Autowired ProductRepository products;
@Autowired JdbcClient jdbc;
@Test void flywayBuiltAnEmptyCatalogue() { assertThat(products.count()).isZero(); }
@Test void findsProductBySkuOnRealMySql() { jdbc.sql("INSERT INTO categories (category_id, name) VALUES (2, 'Mobiles')").update(); jdbc.sql(""" INSERT INTO products (sku, name, category_id, price, stock, is_active) VALUES ('MOB-RN13', 'Redmi Note 13 5G', 2, 17999.00, 40, TRUE)""").update();
assertThat(products.findBySku("MOB-RN13")) .get() .extracting(Product::getName) .isEqualTo("Redmi Note 13 5G"); }}$ ./mvnw verify -Dit.test=ProductRepositoryMySqlIT [INFO] --- failsafe:3.5.6:integration-test (default) @ shoplite-api --- [INFO] Running com.shoplite.product.ProductRepositoryMySqlIT ... [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 19.84 s -- in com.shoplite.product.ProductRepositoryMySqlIT [INFO] BUILD SUCCESS
What this code does
- The
static@Containerfield gives one MySQL for both tests;@DynamicPropertySourcepasses its random URL, user and password to Spring before the DataSource is built, so Flyway creates ShopLite's tables in it. - No profile is active, so no sample rows are loaded and the first test sees an empty catalogue. The second test arranges its own rows with
JdbcClient, using the Section 12 schema. The class ends inIT, so the Failsafe plugin runs it during./mvnw verify, as in Section 16.
@Testcontainers turns on the JUnit extension, which starts every @Container field before the tests. A static field means one container for the whole class; a non-static field would start a new container for every test method.
new MySQLContainer("mysql:8.4") describes a MySQL with a database, user and password (all test by default). It is reachable on a random port, so the URL is known only at run time, which is why @DynamicPropertySource passes mysql::getJdbcUrl and the other values to Spring.
Order of execution
What happens when the class starts
Tap the steps in the order they happen.
What happens when the test runs
Ryuk is a small helper container that Testcontainers starts first. It watches the test JVM and removes every container the tests created when the JVM ends, even after a crash or a killed build.
On the first run Testcontainers connects to Docker, pulls mysql:8.4 and starts it. Read the log below from top to bottom.
Example 2 · The log of a first run
Runs in: the shoplite-api project, ./mvnw verify with Docker running
./mvnw verify -Dit.test=ProductRepositoryMySqlITINFO org.testcontainers.DockerClientFactory -- Testcontainers version: 2.0.5 INFO org.testcontainers.DockerClientFactory -- Connected to docker: Server Version: 28.3.2 API Version: 1.51 Operating System: Docker Desktop Total Memory: 7837 MB INFO tc.testcontainers/ryuk:0.12.0 -- Creating container for image: testcontainers/ryuk:0.12.0 INFO tc.testcontainers/ryuk:0.12.0 -- Container testcontainers/ryuk:0.12.0 started in PT0.71S INFO org.testcontainers.utility.RyukResourceReaper -- Ryuk started - will monitor and terminate Testcontainers containers on JVM exit INFO tc.mysql:8.4 -- Pulling docker image: mysql:8.4. Please be patient; this may take some time but only needs to be done once. INFO tc.mysql:8.4 -- Image mysql:8.4 pull took PT41.2S INFO tc.mysql:8.4 -- Creating container for image: mysql:8.4 INFO tc.mysql:8.4 -- Container mysql:8.4 is starting: 3f9c1e27a0d4 INFO tc.mysql:8.4 -- Waiting for database connection to become available at jdbc:mysql://localhost:55012/test using query 'SELECT 1' INFO tc.mysql:8.4 -- Container mysql:8.4 started in PT13.4S INFO tc.mysql:8.4 -- Container is started (JDBC URL: jdbc:mysql://localhost:55012/test) INFO o.f.core.internal.command.DbMigrate -- Successfully applied 2 migrations to schema `test`, now at version v2
What this code does
- Read it top to bottom: connect to Docker, start Ryuk (the clean-up helper), pull MySQL once (41 s here), start it, wait for
SELECT 1, then Flyway migrates. On the next run the pull line disappears. - The JDBC URL shows the random host port 55012 and the default database
test. Versions and times differ on your machine.
Example 3 · Why random ports never collide
import java.io.IOException;import java.net.ServerSocket;
public class RandomPortDemo { public static void main(String[] args) throws IOException { // Port 0 = "give me any free port", which is what Docker does for Testcontainers try (ServerSocket shopliteTests = new ServerSocket(0); ServerSocket otherProjectTests = new ServerSocket(0)) { int a = shopliteTests.getLocalPort(); int b = otherProjectTests.getLocalPort(); System.out.println("both got a port above 1023: " + (a > 1023 && b > 1023)); System.out.println("ports are different : " + (a != b)); }
try (ServerSocket first = new ServerSocket(0)) { int taken = first.getLocalPort(); try (ServerSocket second = new ServerSocket(taken)) { System.out.println("fixed port twice: worked"); } catch (IOException e) { System.out.println("fixed port twice: " + e.getClass().getSimpleName()); } } }}both got a port above 1023: true ports are different : true fixed port twice: BindException
What this code does
- Asking for port 0 lets the operating system choose a free port, so two test runs at once always get different ports. Docker does the same for each Testcontainers container.
- Asking for the same fixed port twice fails with
BindException, the Java form of "port is already allocated". That is the conflict hard-coded ports cause.
MySQL's port 3306 is published on a random free host port, for example 55012. Testcontainers waits until MySQL answers SELECT 1, and only then the test starts.
You never pick a port, so two projects, or two builds on one CI server, cannot fight over port 3306.
@DataJpaTest with replace = NONE
Replace.NONE is the value of @AutoConfigureTestDatabase(replace = ...) that tells a @DataJpaTest to keep the DataSource you configured instead of swapping in an embedded database such as H2.
A @DataJpaTest normally replaces the DataSource with an embedded database. One annotation keeps ShopLite's MySQL container instead.
Example 4 · src/test/java/com/shoplite/product/ProductRepositoryDataJpaIT.java
Runs in: the shoplite-api Spring Boot project with Docker running
package com.shoplite.product;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase;import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase.Replace;import org.springframework.test.context.DynamicPropertyRegistry;import org.springframework.test.context.DynamicPropertySource;import org.springframework.test.context.jdbc.Sql;import org.testcontainers.junit.jupiter.Container;import org.testcontainers.junit.jupiter.Testcontainers;import org.testcontainers.mysql.MySQLContainer;
@DataJpaTest@AutoConfigureTestDatabase(replace = Replace.NONE) // keep the MySQL DataSource@Testcontainersclass ProductRepositoryDataJpaIT {
@Container static MySQLContainer mysql = new MySQLContainer("mysql:8.4");
@DynamicPropertySource static void databaseProperties(DynamicPropertyRegistry registry) { registry.add("spring.datasource.url", mysql::getJdbcUrl); registry.add("spring.datasource.username", mysql::getUsername); registry.add("spring.datasource.password", mysql::getPassword); }
@Autowired ProductRepository products;
@Test @Sql(statements = { "INSERT INTO categories (category_id, name) VALUES (2, 'Mobiles')", "INSERT INTO products (sku, name, category_id, price, stock, is_active) " + "VALUES ('MOB-RN13', 'Redmi Note 13 5G', 2, 17999.00, 40, TRUE)" }) void skuLookupIgnoresCaseLikeProduction() { // utf8mb4_0900_ai_ci: MySQL matches 'mob-rn13' to 'MOB-RN13' assertThat(products.findBySku("mob-rn13")).isPresent(); }}[INFO] Running com.shoplite.product.ProductRepositoryDataJpaIT ... [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 15.02 s -- in com.shoplite.product.ProductRepositoryDataJpaIT
What this code does
@DataJpaTeststarts only the JPA slice and rolls each test back;replace = Replace.NONEkeeps the container's DataSource instead of an embedded database.@Sqlinserts the rows inside the test's transaction, so they are rolled back with it. The test pins a real MySQL fact: with the case-insensitive collation, a SKU typed in lower case is found. On a case-sensitive H2 the same assertion fails, which is exactly the kind of difference these tests exist to show.
Newer Spring Boot versions are smarter here, but writing it out makes the intent clear and is required on older ones. The rest of the slice works as in Section 18: only JPA, Flyway and the repositories start, and each test is rolled back, so tests do not see each other's rows.
Predict the output
Which database does the test use?
H2 is also on the test classpath. Pick the database the repository test talks to.
Round 1 of 2
A container starts, but the slice keeps its default.
Errors: no Docker, slow first pull, port conflicts
Three problems appear again and again: no Docker, a slow first run and a port conflict. Here is the first one, with the log you will see.
$ ./mvnw verify...java.lang.IllegalStateException: Could not find a valid Docker environment. Please see logs and check configuration$ docker info --format "{{.ServerVersion}}" # does Docker answer at all?Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?# fix: start Docker Desktop (or: sudo systemctl start docker), then$ docker info --format "{{.ServerVersion}}"28.3.2Could not find a valid Docker environment means Testcontainers cannot talk to a Docker engine. Start Docker Desktop and check docker info in the same terminal. On Linux, add your user to the docker group and log in again; in CI, use a runner that has Docker, such as ubuntu-latest.
The first run is slow because the MySQL image is downloaded; run docker pull mysql:8.4 once on a good connection. A port conflict such as "port 3306 is already allocated" cannot happen, because Testcontainers asks Docker for a free port; if you see one, someone hard-coded a port in the test.
Find the bug
Find the setup mistake
Each snippet runs but is wrong. Tap the line with the mistake.
The suite starts a new MySQL for every test method.
Round 1 of 2Next step
Check your understanding
12 quick questions