Practice: Testcontainers
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Your ShopLite integration suite can be slow, flaky or green for the wrong reasons. This optional checkpoint practises four fixes: expose an H2-only bug, use @ServiceConnection, share one container and make tests independent.
Spot the H2-only bug and expose it
An exposing test is a small test that fails on the real engine and proves a bug that a weaker setup, such as H2, hid. After the fix it stays as the regression test.
A bug H2 hides lives in SQL that depends on MySQL's behaviour. To expose it, run that exact query on mysql:8.4.
Example 1 · An H2-only bug and the MySQL test that exposes it
Runs in: the shoplite-api Spring Boot project with Docker running
// ProductRepository.java: green on H2, broken on MySQL@Query(value = """ SELECT * FROM products WHERE product_id IN ( SELECT oi.product_id FROM order_items oi JOIN orders o ON o.order_id = oi.order_id ORDER BY o.ordered_at DESC LIMIT 5)""", nativeQuery = true)List<Product> findRecentlyOrdered();
// RecentlyOrderedIT.java@DataJpaTest@AutoConfigureTestDatabase(replace = Replace.NONE)@Import(MySqlTestcontainersConfig.class)@ActiveProfiles("test")class RecentlyOrderedIT {
@Autowired ProductRepository products;
@Test @Sql("/sql/three-recent-orders.sql") void returnsProductsOfRecentOrders() { assertThat(products.findRecentlyOrdered()) .extracting(Product::getSku) .containsExactlyInAnyOrder("MOB-RN13", "ACC-AD141", "BK-CLEAN"); }}[ERROR] returnsProductsOfRecentOrders <<< ERROR! org.springframework.dao.InvalidDataAccessResourceUsageException: JDBC exception executing SQL [...] [This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'] (after wrapping the LIMIT query in a derived table) [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 -- in com.shoplite.product.RecentlyOrderedIT
What this code does
- The test arranges three recent orders with one script and asserts the products a customer would see. On MySQL it fails with error 1235, proving the bug H2 hid.
- After the fix (a derived table:
SELECT recent.product_id FROM (... LIMIT 5) AS recent) the same test passes and stays as the regression test.
A native query, a comparison affected by collation or a DECIMAL result are the usual suspects. Keep the test small: arrange a few rows with @Sql, call the repository method once, assert one fact. If it fails on MySQL and passed on H2, you have proved the bug.
Convert @DynamicPropertySource to @ServiceConnection
The conversion is mechanical: annotate the container with @ServiceConnection, delete the property method, then move the container into the shared configuration.
// before@Containerstatic MySQLContainer mysql = new MySQLContainer("mysql:8.4");
@DynamicPropertySourcestatic void props(DynamicPropertyRegistry r) { r.add("spring.datasource.url", mysql::getJdbcUrl); r.add("spring.datasource.username", mysql::getUsername); r.add("spring.datasource.password", mysql::getPassword);}
// after: no field at all, one line on the class@Import(MySqlTestcontainersConfig.class)Keep @DynamicPropertySource only for properties that Boot cannot derive from a container, such as the URL of a mock server you started yourself.
Fix a suite that starts a new container per class
If the log shows Container mysql:8.4 started once per test class, each class owns its container. With 20 classes at 12 seconds each, that is four minutes of waiting.
Example 2 · Counting container starts in a test log
import java.util.List;
public class ContainerStartCounterDemo { static long starts(List<String> log) { return log.stream().filter(l -> l.contains("Container mysql:8.4 started")).count(); }
public static void main(String[] args) { List<String> before = List.of( "Running ProductRepositoryIT", "Container mysql:8.4 started in PT12.1S", "Running CategoryRepositoryIT", "Container mysql:8.4 started in PT11.8S", "Running OrderApiIT", "Container mysql:8.4 started in PT12.4S"); List<String> after = List.of( "Running ProductRepositoryIT", "Container mysql:8.4 started in PT12.0S", "Running CategoryRepositoryIT", "Running OrderApiIT");
System.out.println("before: " + starts(before) + " starts for 3 classes"); System.out.println("after : " + starts(after) + " start for 3 classes"); }}before: 3 starts for 3 classes after : 1 start for 3 classes
What this code does
- Counting the
startedlines is the quickest health check for a Testcontainers suite: the goal is one start per run, or one per distinct context if you must have several. - The "after" log comes from the same three classes importing one
MySqlTestcontainersConfigwith identical configuration.
Example 3 · Before and after: per-class containers to one shared configuration
Runs in: the shoplite-api Spring Boot project with Docker running
// BEFORE: repeated in 20 test classes, one container each@DataJpaTest@AutoConfigureTestDatabase(replace = Replace.NONE)@Testcontainersclass ProductRepositoryIT { @Container @ServiceConnection static MySQLContainer mysql = new MySQLContainer("mysql:8.4"); @Test void checks() { }}
// AFTER: the same two lines on every repository test, one container for all of them@DataJpaTest@AutoConfigureTestDatabase(replace = Replace.NONE)@Import(MySqlTestcontainersConfig.class)class ProductRepositoryIT { @Test void checks() { }}before: [INFO] Tests run: 86, Failures: 0, Errors: 0, Skipped: 0 Total time: 04:12 min after : [INFO] Tests run: 86, Failures: 0, Errors: 0, Skipped: 0 Total time: 41.3 s
What this code does
- Each class with its own
@Containerfield starts and stops its own MySQL. Moving the container into one imported configuration lets the context cache share it. - The test count is unchanged; only the waiting is gone. Your times will differ, but the drop is usually this large.
The cause is a @Container field in every class, or contexts that differ. The fix is one shared container: a single @TestConfiguration imported everywhere with identical test configuration, or a singleton container in a base class. Then count again: the log should show one start for the whole run.
Tests that pass alone but fail together
A test that passes alone and fails in the full suite relies on the database looking a certain way, and another test changed it. Run the model to see it.
Example 4 · Pass alone, fail together: a model and the fix
import java.util.ArrayList;import java.util.List;
public class SharedDbOrderDemo { static List<String> customers = new ArrayList<>(); // the shared database
static boolean signUpCreatesCustomer() { // order-dependent version customers.add("asha.rao@example.com"); return customers.size() == 1; }
static boolean signUpCreatesCustomerFixed(String uniqueEmail) { customers.add(uniqueEmail); return customers.contains(uniqueEmail); }
static void otherTestLeavesARow() { customers.add("ravi.kumar@example.com"); // committed over HTTP, never cleaned }
public static void main(String[] args) { System.out.println("alone : " + signUpCreatesCustomer());
customers.clear(); otherTestLeavesARow(); System.out.println("together: " + signUpCreatesCustomer());
customers.clear(); otherTestLeavesARow(); System.out.println("fixed : " + signUpCreatesCustomerFixed("asha+t1@example.com")); }}alone : true together: false fixed : true
What this code does
- Alone, the database is empty and
size() == 1holds. After another test leaves a committed row, the same assertion fails, though the code under test is correct. - The fixed test inserts a unique email and asserts only on it, so leftovers no longer matter. A clean-up
@Sqlafter each HTTP test removes the leftovers themselves.
Typical signs are assertions on count(), on the first row of findAll() or on generated ids, and unique-constraint errors for data another test also inserted.
The fixes come from the shared-container lesson: roll back where you can, clean up after HTTP tests with an @Sql script, and give each test unique data that it alone asserts on.
Interview drill: why Testcontainers, and who cleans up
Practise both answers in about 60 seconds each.
- Why Testcontainers over H2? H2 is a different engine; functions, collation, DECIMAL scale and syntax such as LIMIT in subqueries differ, so H2 tests can pass while MySQL fails. Testcontainers runs the same engine and version as production, migrated by the same Flyway scripts, at the cost of Docker and a few seconds per run.
- How are containers cleaned up? The JUnit extension or the Spring context stops the containers it started, and Ryuk, a helper container, removes anything left when the JVM exits, even after a crash. Reused containers are the exception and belong only on developer machines.
Finish up
Mark complete & continue
Next: Project: ShopLite repository tests on real MySQL