Skip to content

Spring Boot Test Containers

DodaTech 1 min read

In this tutorial, you'll learn about Fix Spring Boot Testcontainers Not Starting. We cover key concepts, practical examples, and best practices.

The Problem

The Testcontainer fails to start or the application cannot connect.

Quick Fix

Add @Testcontainers

Wrong:

// @Testcontainers not on class

Output:

Container not managed

Right:

@Testcontainers
class DatabaseTest { }

Output:

Testcontainers lifecycle managed

Declare @Container

Wrong:

// Container not declared

Output:

No container started

Right:

@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15");

Output:

Container started

Configure dynamic properties

Wrong:

// Properties not set

Output:

App cannot connect

Right:

@DynamicPropertySource
static void props(DynamicPropertyRegistry r) {
    r.add("spring.datasource.url", postgres::getJdbcUrl);
}

Output:

App connects to container

Prevention

  • Use @Testcontainers on the test class
  • Declare @Container static fields
  • Use DynamicPropertySource to set connection properties

Common Mistakes with boot test containers

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world SPRING code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does Testcontainers fail with Docker not found?

Ensure Docker is running and the Testcontainers Docker socket is accessible.

This quick fix is part of the DodaTech Spring & JVM ecosystem series. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro