Skip to lesson

@ServiceConnection and a shared container

ShopLite's test classes each copy a MySQL container and a property method, and each class starts its own MySQL. How can every integration test share one container with almost no code?

@ServiceConnection replaces @DynamicPropertySource

@ServiceConnection is a Spring Boot annotation (from spring-boot-testcontainers) for a container field or bean. Boot reads the container's type and creates its connection details: the JDBC URL, user and password.

The last lesson passed the container's URL to Spring with three registry.add(...) lines. One annotation does the same job here.

Example 1 · The same test with @ServiceConnection

Runs in: the shoplite-api Spring Boot project with Docker running

Java
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.boot.testcontainers.service.connection.ServiceConnection;import org.testcontainers.junit.jupiter.Container;import org.testcontainers.junit.jupiter.Testcontainers;import org.testcontainers.mysql.MySQLContainer;
@SpringBootTest@Testcontainersclass ProductRepositoryMySqlIT {
    @Container    @ServiceConnection                     // replaces the @DynamicPropertySource method    static MySQLContainer mysql = new MySQLContainer("mysql:8.4");
    @Autowired    ProductRepository products;
    @Test    void flywayBuiltAnEmptyCatalogue() {        assertThat(products.count()).isZero();    }}
Sample output
[INFO] Running com.shoplite.product.ProductRepositoryMySqlIT
INFO  tc.mysql:8.4 -- Container is started (JDBC URL: jdbc:mysql://localhost:55021/test)
INFO  o.f.core.internal.command.DbMigrate -- Successfully applied 2 migrations to schema `test`, now at version v2
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 17.66 s -- in com.shoplite.product.ProductRepositoryMySqlIT

What this code does

  • @ServiceConnection on the container makes Spring Boot create the JDBC connection details from it, so the DataSource uses the container's random URL, user and password without any property code.
  • The log shows Flyway migrating the container's test database: the wiring worked.

Boot looks at the container's type, here MySQLContainer, and the DataSource, Flyway and Hibernate use the connection details it creates. Boot also knows the right properties for other containers, such as PostgreSQL or Redis, so you no longer remember property names.

One @TestConfiguration, imported by every test

@TestConfiguration is a configuration class used only in tests. A container declared there as a @Bean with @ServiceConnection starts with the test context and stops when the context closes.

Copying a container field into every class repeats code and starts a MySQL per class. Put the container in one test configuration and import it.

Example 2 · src/test/java/com/shoplite/MySqlTestcontainersConfig.java and a test that imports it

Runs in: the shoplite-api Spring Boot project with Docker running

MySqlTestcontainersConfig.javaJava
// ---- src/test/java/com/shoplite/MySqlTestcontainersConfig.java ----package com.shoplite;
import org.springframework.boot.test.context.TestConfiguration;import org.springframework.boot.testcontainers.service.connection.ServiceConnection;import org.springframework.context.annotation.Bean;import org.testcontainers.mysql.MySQLContainer;
@TestConfiguration(proxyBeanMethods = false)public class MySqlTestcontainersConfig {
    public static final String MYSQL_IMAGE = "mysql:8.4";
    @Bean    @ServiceConnection    MySQLContainer mysqlContainer() {        return new MySQLContainer(MYSQL_IMAGE);    }}
// ---- src/test/java/com/shoplite/category/CategoryRepositoryIT.java ----@DataJpaTest@AutoConfigureTestDatabase(replace = Replace.NONE)@Import(MySqlTestcontainersConfig.class)class CategoryRepositoryIT {
    @Autowired    CategoryRepository categories;
    @Test    @Sql(statements = "INSERT INTO categories (name) VALUES ('Mobiles')")    void findsCategoryByName() {        assertThat(categories.findByName("mobiles")).isPresent();   // _ci collation    }}
Sample output
[INFO] Running com.shoplite.category.CategoryRepositoryIT
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 16.12 s -- in com.shoplite.category.CategoryRepositoryIT

What this code does

  • The container is a bean, so there is no @Testcontainers or @Container in the test: Spring Boot starts the bean before the DataSource needs it and stops it with the context.
  • proxyBeanMethods = false is the usual setting for configuration classes whose @Bean methods do not call each other; it makes start-up a little lighter.

Each test class then needs one line, @Import(MySqlTestcontainersConfig.class), instead of a container field. The image tag lives in one place, so moving every test to a new MySQL version is a one-line change.

Fix the error

Fix the import

Read the real compiler error, then pick the line that fixes it.

A test class should use the shared configuration.

@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
@Import(MySqlTestcontainersConfig)
class CategoryRepositoryIT {

Error

CategoryRepositoryIT.java:3: error: cannot find symbol
@Import(MySqlTestcontainersConfig)
        ^
  symbol:   variable MySqlTestcontainersConfig

Sharing one container across test classes

The context cache is Spring's store of application contexts built for tests. A later test class with exactly the same configuration reuses the cached context, so beans such as the MySQL container are shared.

Spring keeps a test context alive after a class finishes and reuses it when the next class has the same configuration. Run this model to count the containers.

Test classes with identical configuration share one cached Spring context and one MySQL container: ProductRepositoryIT, CategoryRepositoryIT and OrderRepositoryIT. CartIT adds a @MockitoBean, so Spring builds a second context, which starts a second MySQL container.

Example 3 · Context cache: how many containers start?

ContextCacheDemo.javaJava
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class ContextCacheDemo {    record TestClass(String name, String configuration) {}
    public static void main(String[] args) {        Map<String, Integer> contextCache = new LinkedHashMap<>();   // configuration -> container id        int containersStarted = 0;
        List<TestClass> suite = List.of(                new TestClass("ProductRepositoryIT", "DataJpa + MySqlConfig"),                new TestClass("CategoryRepositoryIT", "DataJpa + MySqlConfig"),                new TestClass("OrderRepositoryIT", "DataJpa + MySqlConfig"),                new TestClass("OrderApiIT", "SpringBootTest + MySqlConfig"),                new TestClass("CustomerApiIT", "SpringBootTest + MySqlConfig + MockitoBean(MailSender)"));
        for (TestClass t : suite) {            Integer container = contextCache.get(t.configuration());            if (container == null) {                containersStarted++;                container = containersStarted;                contextCache.put(t.configuration(), container);                System.out.printf("%-20s new context  -> starts MySQL #%d%n", t.name(), container);            } else {                System.out.printf("%-20s cached context -> reuses MySQL #%d%n", t.name(), container);            }        }        System.out.println("Containers started: " + containersStarted);    }}
Output
ProductRepositoryIT  new context  -> starts MySQL #1
CategoryRepositoryIT cached context -> reuses MySQL #1
OrderRepositoryIT    cached context -> reuses MySQL #1
OrderApiIT           new context  -> starts MySQL #2
CustomerApiIT        new context  -> starts MySQL #3
Containers started: 3

What this code does

  • Classes with an identical configuration share one cached context and its container. A different slice (@SpringBootTest instead of @DataJpaTest) is a different context and gets its own MySQL.
  • One extra @MockitoBean in CustomerApiIT changes the configuration, so it starts a third container. This is a simplified model of Spring's cache key, but the effect is real.

Example 4 · The singleton container pattern

Runs in: the shoplite-api Spring Boot project with Docker running

MySqlIntegrationTest.javaJava
// ---- src/test/java/com/shoplite/MySqlIntegrationTest.java ----package com.shoplite;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;import org.testcontainers.mysql.MySQLContainer;
public abstract class MySqlIntegrationTest {
    @ServiceConnection    static final MySQLContainer MYSQL = new MySQLContainer("mysql:8.4");
    static {        MYSQL.start();   // once per JVM; Ryuk removes it when the test run ends    }}
// ---- every integration test extends it ----@SpringBootTestclass OrderApiIT extends MySqlIntegrationTest {    @Test    void placesOrder() {}}
Sample output
[INFO] Running com.shoplite.order.OrderApiIT
INFO  tc.mysql:8.4 -- Container is started (JDBC URL: jdbc:mysql://localhost:55030/test)
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 21.40 s -- in com.shoplite.order.OrderApiIT
[INFO] Running com.shoplite.customer.CustomerApiIT
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.87 s -- in com.shoplite.customer.CustomerApiIT

What this code does

  • The static block runs once, when the first subclass is loaded, so the whole test run uses one MySQL even when Spring creates several contexts. Spring Boot finds the @ServiceConnection field in the superclass.
  • There is no @Testcontainers/@Container here on purpose: the JUnit extension would stop the container after each class. Note how the second class needs no container start at all.

Any difference, such as an extra @MockitoBean or a different @TestPropertySource, creates a new context and therefore a new container, so keep the integration tests' configuration identical.

The other common pattern is a singleton container: a static final container in an abstract base class, started once in a static block. It lives for the whole JVM whatever the contexts do, and Ryuk removes it at the end.

Predict the output

How many MySQL containers start?

All classes use the config bean from this lesson. Pick the number of containers.

Round 1 of 3

Three repository tests with identical annotations.

@DataJpaTest @Import(MySqlTestcontainersConfig.class)
class ProductRepositoryIT { }
@DataJpaTest @Import(MySqlTestcontainersConfig.class)
class CategoryRepositoryIT { }
@DataJpaTest @Import(MySqlTestcontainersConfig.class)
class OrderRepositoryIT { }

Running the app locally: TestShopliteApiApplication

SpringApplication.from is a Spring Boot method that runs the real application's main method; .with(...) adds extra configuration, such as a MySQL container bean, so the app starts on a throw-away database.

The same container configuration can start ShopLite on your laptop with a fresh MySQL, without Compose. TestShopliteApiApplication does it in a few lines.

Example 5 · src/test/java/com/shoplite/TestShopliteApiApplication.java

Runs in: the shoplite-api Spring Boot project with Docker running

TestShopliteApiApplication.javaJava
package com.shoplite;
import org.springframework.boot.SpringApplication;
public class TestShopliteApiApplication {
    public static void main(String[] args) {        SpringApplication.from(ShopliteApiApplication::main)    // the real app's main method                .with(MySqlTestcontainersConfig.class)        // plus the MySQL container bean                .run(args);    }}
Sample output
$ ./mvnw spring-boot:test-run -Dspring-boot.run.profiles=dev
...
INFO  tc.mysql:8.4 -- Container is started (JDBC URL: jdbc:mysql://localhost:55044/test)
INFO  o.f.core.internal.command.DbMigrate -- Successfully applied 3 migrations to schema `test`, now at version v2
INFO  o.s.b.w.e.tomcat.TomcatWebServer -- Tomcat started on port 8080 (http) with context path '/'
INFO  com.shoplite.TestShopliteApiApplication -- Started TestShopliteApiApplication in 19.73 seconds

$ curl -s "http://localhost:8080/api/v1/products?page=0&size=1"
{"content":[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}],"page":0,"size":1,"totalElements":15,"totalPages":15}

What this code does

  • spring-boot:test-run runs this class with the test classpath. The dev profile loads the sample rows (3 migrations including the dev-data one), so the API answers with real ShopLite products.
  • Every start gives a fresh, empty-then-migrated database, which is handy for demos. Stopping the app stops the container and the data is gone.

Run it from the IDE or with ./mvnw spring-boot:test-run. The container starts first and the DataSource points at it. The class lives in src/test, so it never reaches the production jar.

Keeping tests independent on a shared database

An order-dependent test passes or fails depending on which tests ran before it, because it relies on database rows that another test created or removed.

A shared database means one test's rows can be seen by the next test. Unique test data is the simplest cure, and this model shows it.

Example 6 · Unique test data that never collides

UniqueTestDataDemo.javaJava
import java.util.HashSet;import java.util.Set;import java.util.concurrent.atomic.AtomicInteger;
public class UniqueTestDataDemo {    static final AtomicInteger SEQUENCE = new AtomicInteger();
    static String uniqueSku(String prefix) {        return String.format("%s-T%04d", prefix, SEQUENCE.incrementAndGet());    }
    static String uniqueEmail(String name) {        return name + "+t" + SEQUENCE.incrementAndGet() + "@example.com";    }
    public static void main(String[] args) {        Set<String> usedInSharedDb = new HashSet<>();        for (String testName : new String[] {"placeOrder", "cancelOrder", "placeOrder (re-run)"}) {            String sku = uniqueSku("MOB");            String email = uniqueEmail("asha");            boolean clash = !usedInSharedDb.add(sku) | !usedInSharedDb.add(email);            System.out.println(testName + ": " + sku + ", " + email + (clash ? "  CLASH" : ""));        }    }}
Output
placeOrder: MOB-T0001, asha+t2@example.com
cancelOrder: MOB-T0003, asha+t4@example.com
placeOrder (re-run): MOB-T0005, asha+t6@example.com

What this code does

  • Every call takes the next number, so no two tests, and no re-run in the same JVM, create the same SKU or email. A unique constraint on sku or email can never fail because of another test's leftovers.
  • Tests that use unique data assert on their own rows (findBySku(sku)), not on totals such as count(), which other tests change.

Three tools keep tests independent:

  • Rollback: @DataJpaTest (and @Transactional on a test) roll back each test's changes. It does not work for @SpringBootTest(webEnvironment = RANDOM_PORT), because the HTTP request runs in another thread whose transaction commits.
  • Cleaning tables: an @Sql script that deletes rows after each test, children first.
  • Unique test data: each test creates rows with its own SKUs or emails and asserts only on those.

Find the bug

Find the order-dependent line

Each test passes alone but fails in the full run. Tap the line that causes it.

The test adds one product to the shared database.

Round 1 of 3

Next step

Check your understanding

12 quick questions