TL;DR: An in-memory H2 database and an embedded broker only prove that your code works against something like production. Testcontainers gives JUnit tests a real PostgreSQL and a real Kafka in Docker. With Spring Boot’s
@ServiceConnection, it takes about ten lines of config.
Generated AI image by Google Gemini Nano Banana
Introduction
We’ve all had this build: every test is green, the pipeline is fast, and the team ships with confidence. Then the first deploy hits a real PostgreSQL instance and falls over with ERROR: column "metadata" is of type jsonb but expression is of type character varying.
The tests weren’t lying, exactly. They were answering a different question. H2 told you your code works against H2.
I spent a long stretch of my career in Australian banking, where that gap matters a lot. A test that passes in memory and fails in production isn’t a flaky test. It’s an incident report. So as part of my Java comeback series, I’ve been rebuilding my integration-testing habits around Testcontainers: real infrastructure, started in Docker, managed by JUnit.
In this post, we’ll replace H2 and the embedded Kafka broker with the real thing. Whether you’re maintaining a Spring Boot service or just tired of “works on my H2,” you’ll find patterns you can apply on Monday.
By the end of this post, you’ll understand:
- Why in-memory fakes give you false confidence, with a concrete example
- How to wire real PostgreSQL and Kafka into JUnit tests using Testcontainers 2.x and Spring Boot’s
@ServiceConnection - How to keep those tests fast enough that your team actually runs them
A quick note on versions: The title says “JUnit,” not “JUnit 5,” on purpose. JUnit 6 shipped on 30 September 2025 with a Java 17 baseline. The Jupiter programming model (
@Test,@BeforeEach, extensions) is the same one you know from JUnit 5. Spring Boot 4 uses JUnit 6 by default. Everything below works on either, as long as you’re on Jupiter.The examples target Spring Boot 4.x (4.1 is the current stable line, and 4.2 is due later this month), Testcontainers 2.0.x and JUnit 6.1.x. If you’re still on Boot 3.5, note that its free OSS support ended on 30 June 2026. It also manages Testcontainers 1.x, so the 1.x artifact names and packages apply there.
Section 1: Why H2 Lies to You
The compatibility-mode trap
H2’s MODE=PostgreSQL is a best-effort imitation, not a promise. It handles basic DDL and simple queries, but production schemas rarely stay basic. Here’s a real-world payments table and a query that any Postgres-backed fintech service might run:
-- src/main/resources/db/migration/V1__payments.sql
CREATE TABLE payments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
idempotency_key TEXT NOT NULL UNIQUE,
order_id UUID NOT NULL,
amount NUMERIC(19, 4) NOT NULL,
status TEXT NOT NULL DEFAULT 'PENDING',
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Partial index: only index the rows we actually poll for
CREATE INDEX idx_payments_pending ON payments (created_at) WHERE status = 'PENDING';
// Idempotent insert + JSONB filtering: everyday Postgres, unsupported or unreliable in H2
@Repository
public class PaymentRepository {
private final JdbcClient jdbc;
public PaymentRepository(JdbcClient jdbc) {
this.jdbc = jdbc;
}
/** Returns 1 if inserted, 0 if this idempotency key was already processed. */
public int recordPayment(String idempotencyKey, UUID orderId, BigDecimal amount, String metadataJson) {
return jdbc.sql("""
INSERT INTO payments (idempotency_key, order_id, amount, metadata)
VALUES (:key, :orderId, :amount, CAST(:metadata AS jsonb))
ON CONFLICT (idempotency_key) DO NOTHING
""")
.param("key", idempotencyKey)
.param("orderId", orderId)
.param("amount", amount)
.param("metadata", metadataJson)
.update();
}
public long countByChannel(String channel) {
return jdbc.sql("SELECT count(*) FROM payments WHERE metadata ->> 'channel' = :channel")
.param("channel", channel)
.query(Long.class)
.single();
}
}
Key points:
JSONBand the->>operator are PostgreSQL features. H2 has its own JSON type with different semantics.ON CONFLICT ... DO NOTHINGis the backbone of idempotent payment processing. If your tests can’t exercise it faithfully, you aren’t testing your idempotency guarantee.- Partial indexes,
gen_random_uuid(),TIMESTAMPTZbehave differently, or not at all, depending on H2 version and mode.
The usual workaround is a second set of “H2-friendly” migrations. At that point, you’re maintaining a fake schema to test fake behaviour. That’s the real cost.
Section 2: Real Infrastructure with Testcontainers 2.x
Testcontainers is a Java library that starts throwaway Docker containers for your tests and cleans them up afterwards. Its sidecar, Ryuk, removes containers even if the JVM crashes. You need a Docker-compatible runtime locally and in CI. GitHub Actions’ Ubuntu runners already have one.
Dependencies (and the 2.0 rename gotcha)
Testcontainers 2.0 renamed every module artifact to use a consistent testcontainers- prefix. It also moved container classes into per-module packages and removed JUnit 4 support. Old blog posts (and your AI assistant) will happily give you org.testcontainers:postgresql. The 2.x BOM doesn’t manage it, so Maven fails with a missing-version error.
Spring Boot 4 also split auto-configuration into modules. Having flyway-core on the classpath no longer auto-configures Flyway, so you need the starters explicitly:
<!-- pom.xml (main): Boot 4 needs explicit starters for Flyway, JDBC and Kafka -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-flyway</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId> <!-- Flyway 10+ ships DB support as separate modules -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId> <!-- JdbcClient -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-kafka</artifactId> <!-- Boot 4: replaces a bare spring-kafka dependency -->
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
Then the test-scoped Testcontainers modules:
<!-- pom.xml (test): Spring Boot 4 manages the Testcontainers 2.x version for you -->
<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> <!-- 1.x: junit-jupiter -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-postgresql</artifactId> <!-- 1.x: postgresql -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-kafka</artifactId> <!-- 1.x: kafka -->
<scope>test</scope>
</dependency>
If you’re upgrading an existing codebase, OpenRewrite has a Testcontainers2Dependencies recipe that renames these for you.
Plain JUnit: no Spring required
The core model is two annotations. @Testcontainers enables the JUnit extension. @Container marks the containers it manages. A static field means one container for the whole class instead of one per test method.
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.postgresql.PostgreSQLContainer; // 2.x package (1.x: org.testcontainers.containers)
import java.sql.DriverManager;
import static org.assertj.core.api.Assertions.assertThat;
@Testcontainers
class PostgresSmokeTest {
@Container
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18-alpine"); // pin the tag to your prod major!
@Test
void jsonbOperatorsWorkBecauseThisIsRealPostgres() throws Exception {
try (var conn = DriverManager.getConnection(
postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword());
var rs = conn.createStatement()
.executeQuery("SELECT '{\"channel\":\"mobile\"}'::jsonb ->> 'channel'")) {
rs.next();
assertThat(rs.getString(1)).isEqualTo("mobile");
}
}
}
Section 3: Spring Boot + @ServiceConnection
Before Spring Boot 3.1, you wired containers into Spring with @DynamicPropertySource, copying JDBC URLs and bootstrap servers into properties by hand. @ServiceConnection does that for you. Spring Boot recognises the container type and builds the connection details automatically.
One shared configuration for the whole suite
Rather than declaring containers in every test class, define them once as beans:
@TestConfiguration(proxyBeanMethods = false)
public class TestcontainersConfig {
@Bean
@ServiceConnection // -> spring.datasource.* (Flyway runs your real migrations against it)
PostgreSQLContainer postgres() {
return new PostgreSQLContainer("postgres:18-alpine");
}
@Bean
@ServiceConnection // -> spring.kafka.bootstrap-servers
KafkaContainer kafka() {
// org.testcontainers.kafka.KafkaContainer = official apache/kafka image, KRaft mode, no ZooKeeper.
// Using Confluent images? Use ConfluentKafkaContainer instead.
return new KafkaContainer("apache/kafka:4.3.1"); // match your brokers' version
}
}
Because the containers are beans, they share the lifecycle of Spring’s cached application context. Every test class that imports this config and has the same context setup reuses the same PostgreSQL and Kafka. You don’t pay a container startup per class.
Bonus: the same config gives you a local dev environment. Point a TestApplication main method at SpringApplication.from(Application::main).with(TestcontainersConfig.class).run(args), and ./mvnw spring-boot:test-run boots your app with real infrastructure. No docker-compose.yml to keep in sync.
Real-World Example: Idempotent Payment Events End to End
Let’s test the full flow. A payment-events message arrives on Kafka, a listener persists it, and a duplicate delivery must not create a second row. This is at-least-once delivery, the thing that keeps payment engineers up at night.
@Component
class PaymentEventListener {
private final PaymentRepository payments;
PaymentEventListener(PaymentRepository payments) {
this.payments = payments;
}
// Message key = idempotency key; value = "orderId,amount,channel" (kept simple for the demo)
@KafkaListener(topics = "payment-events", groupId = "payments-service")
void onPaymentEvent(ConsumerRecord<String, String> record) {
String[] parts = record.value().split(",");
payments.recordPayment(
record.key(),
UUID.fromString(parts[0]),
new BigDecimal(parts[1]),
"{\"channel\":\"%s\"}".formatted(parts[2]));
}
}
@SpringBootTest(properties = "spring.kafka.consumer.auto-offset-reset=earliest")
@Import(TestcontainersConfig.class)
class PaymentEventFlowIT {
@Autowired KafkaTemplate<String, String> kafka;
@Autowired PaymentRepository payments;
@Autowired JdbcClient jdbc;
@Test
void duplicateDeliveryIsProcessedExactlyOnce() {
String idempotencyKey = "pay-" + UUID.randomUUID(); // unique per test: no cleanup coupling
String payload = UUID.randomUUID() + ",149.95,mobile";
// Simulate Kafka's at-least-once delivery: same event, twice
kafka.send("payment-events", idempotencyKey, payload);
kafka.send("payment-events", idempotencyKey, payload);
// Async consumer: poll instead of Thread.sleep()
await().atMost(Duration.ofSeconds(15)).untilAsserted(() -> {
long rows = jdbc.sql("SELECT count(*) FROM payments WHERE idempotency_key = :k")
.param("k", idempotencyKey)
.query(Long.class)
.single();
assertThat(rows).isEqualTo(1); // ON CONFLICT DO NOTHING, proven against real Postgres
});
assertThat(payments.countByChannel("mobile")).isGreaterThanOrEqualTo(1); // real JSONB query
}
}
This one test exercises real Kafka serialisation, consumer-group offset handling, your actual Flyway migrations, the unique constraint, and the JSONB operator. H2 plus @EmbeddedKafka could only approximate two of those five.
Notice the test generates its own idempotency key instead of truncating tables. Because the containers are shared across the suite, test isolation comes from unique data, not a fresh database. That’s also how your service behaves in production.
Best Practices and Recommendations
Do’s ✅
- Pin image tags (
postgres:18-alpine) to match your production major version, so a surpriselatestupgrade can’t break CI. - Share containers through cached contexts or a singleton config. Startup cost should be paid once per suite, not once per class.
- Name integration tests
*ITand run them with Maven Failsafe. Unit tests stay sub-second and the contract stays clear. - Use Awaitility for anything asynchronous. Kafka consumers don’t finish on your schedule.
Don’ts ❌
- Avoid
@DirtiesContext. It throws away the cached context, and with it your containers, so the next class starts them again. - Don’t keep H2 “just for unit tests” that touch SQL. If it hits a database, it hits the real one.
- Never hardcode ports. Testcontainers maps to random host ports. Always ask the container (
getJdbcUrl(),getBootstrapServers()), or let@ServiceConnectiondo it.
Performance Considerations
Expect a few seconds of startup for PostgreSQL and a little more for Kafka on the first run, plus the one-off image pull. Three levers keep it manageable:
- Context caching, as shown above. This is the biggest win by far.
- Reusable containers for local dev: add
testcontainers.reuse.enable=trueto~/.testcontainers.propertiesand call.withReuse(true)on the container. Containers survive between runs. Keep this off in CI. - Pre-pull images in CI, or cache them, so the pipeline isn’t bound by Docker Hub.
Troubleshooting Guide
| Problem | Cause | Solution |
|---|---|---|
Could not find a valid Docker environment |
No Docker daemon, or socket not visible | Start Docker Desktop / Colima / Podman, check docker info; on Colima, set DOCKER_HOST |
'dependencies.dependency.version' for org.testcontainers:postgresql:jar is missing |
1.x artifact names on a 2.x BOM | Use testcontainers-postgresql, testcontainers-kafka, etc. |
| Migrations never run; tables missing after upgrading to Boot 4 | flyway-core alone no longer auto-configures |
Add spring-boot-starter-flyway (plus flyway-database-postgresql) |
PostgreSQLContainer import doesn’t compile |
Package moved in 2.0 | Import from org.testcontainers.postgresql / org.testcontainers.kafka |
| Kafka test passes locally, times out in CI | Consumer starts after the message is sent | Set auto-offset-reset=earliest and widen the Awaitility timeout |
| Suite gets slower with every new test class | Contexts differ or @DirtiesContext |
Standardise on one @Import(TestcontainersConfig.class) setup |
Further Reading
- Testcontainers for Java: official docs
- Spring Boot reference: Testcontainers and service connections
- Testing a Spring Boot Kafka listener using Testcontainers (Docker guide)
- JUnit 6 release notes
- OpenRewrite: Testcontainers 2 dependency rename recipe
Conclusion
H2 was a reasonable compromise when spinning up a real database for every build was painful. That’s no longer true. With Testcontainers 2.x and @ServiceConnection, real PostgreSQL and real Kafka cost you one config class and a Docker daemon. In return, your idempotency guarantees, JSONB queries, and migrations get tested against the engines that will actually run them.
The bigger shift is mindset. Integration tests should answer “will this work in production?”, not “will this work in a simulator?” In regulated domains like banking, that difference shows up as audit findings and incidents.
Your next steps:
- Find one repository test that runs on H2, move it onto
TestcontainersConfig, and see what breaks. Something usually does. - Delete your H2-specific migration scripts, and the
h2dependency with them. - Add a
*ITFailsafe stage to your pipeline so these tests gate every merge.
What’s the nastiest H2-vs-production surprise you’ve hit? Tell me in the comments. I’m collecting war stories.
Till next time, Happy Coding!