BBackend CourseLeroy Labs
0/0
Search the course

Integration tests with Testcontainers & @ServiceConnection

Real PostgreSQL (and RabbitMQ, Mailpit) in Docker for tests, the singleton-container pattern, abstract base classes, running all migrations, and why H2 is not a substitute.

● intermediateReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

The concept

Testcontainers starts real dependencies in Docker for the test run. With Spring Boot’s @ServiceConnection, the container’s URL and credentials are wired in automatically, with no @DynamicPropertySource boilerplate.

@SpringBootTest
@AutoConfigureMockMvc
@Testcontainers
public abstract class AbstractIntegrationTest {

    @Container
    @ServiceConnection
    static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine");
    // static + reused across all subclasses = "singleton container": started once per JVM

    @Autowired protected MockMvc mvc;
}

class AuditIntegrationTest extends AbstractIntegrationTest {
    @Test void updatingAnAccount_writesBeforeAndAfterAudit() throws Exception {
        // real HTTP -> real security -> real service -> real Liquibase-migrated Postgres
    }
}

Why not H2?

H2 in “Postgres mode” Real Postgres via Testcontainers
Speed Faster startup A few seconds once per suite
PostGIS, JSONB, partial indexes, triggers, advisory locks, FOR UPDATE SKIP LOCKED, CTE quirks ❌ / differs ✅
Your Liquibase SQL scripts Often fail ✅ Run exactly as in prod
Confidence “Works in H2” “Works in Postgres”

SperoTek’s triggers and IR3D’s partial unique indexes can only be tested on real Postgres.

In your projects

Report-Manager-2support/AbstractIntegrationTest.java · AuditIntegrationTest · ApprovalsFollowTheUnitIntegrationTest

@SpringBootTest + @ServiceConnection PostgreSQLContainer<>("postgres:16-alpine") as a singleton, so all 22 Liquibase changesets run in tests, together with Awaitility for async assertions. H2 is also on the classpath, but the important tests use Postgres.

IR3D (Kontentt)support/AbstractIntegrationTest.java · WalletServiceIntegrationTest · AuthFlowIntegrationTest · StaffMfaPolicyIntegrationTest · ErrorShapeIntegrationTest

About 95 test files, mostly integration tests, built on @SpringBootTest @AutoConfigureMockMvc + @ServiceConnection PostgreSQLContainer, with a Testcontainers RabbitMQ dependency available. WalletServiceIntegrationTest exercises the real locking and the ledger.

SperoTek (in dev)AbstractIT → AbstractIdentityIT / AbstractMfaIT / AbstractAccessIT / AbstractLedgerIT · Mailpit.java · application-test.yaml

A hierarchy of base classes, each adding fixtures (a logged-in user, an MFA-enrolled user, a company with members, a company with a chart of accounts). Mailpit is used to assert real emails. Coverage includes tenant isolation, posting, approvals, SSO, passkeys, rate limits, email retry and restart, and a ReportBenchmarkIT performance test. Surefire runs *Test and Failsafe runs *IT separately.

Making them fast and reliable

  • Singleton containers (static, shared) rather than per-class containers.
  • Testcontainers reuse (testcontainers.reuse.enable=true) keeps containers between local runs.
  • Clean data between tests. Options are transactional rollback (@Transactional on the test, which doesn’t work for async code or code that commits), truncating tables in @BeforeEach, or unique ids per test.
  • Spring caches the application context between tests with identical config. Avoid unnecessary @MockitoBean variations, because each new combination creates a new context, which is slow.
  • Docker in CI. GitHub Actions Ubuntu runners have Docker built in. IR3D’s backend-tests.yml and RM’s deploy.yml run ./mvnw test.
  • @ServiceConnection also supports RabbitMQ, Redis, Kafka, Mongo and more.
  • Testcontainers for local dev. spring-boot-testcontainers can start your dev DB through TestApplication, as an alternative to docker-compose.

Check yourself

1. Why can’t SperoTek test its posted-journal triggers with H2?
2. Benefit of a static (singleton) container?