Testing CDC Pipelines
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A migration pipeline has more moving parts than most applications, and most of them are configuration: the source
connector’s include lists and type handling, the topic names, the converters, the sink’s key and delete settings, the
anti-corruption rules that turn ACTIVE_FLG = 'Y' into active = true. A mistake in any of them does not fail a
build. It produces a row that is subtly wrong in the new database, and it is found weeks later by reconciliation, or by
a customer. Automated tests move that discovery to the moment the change is made.
This page shows how to test the Bookshop pipeline at four levels: plain unit tests for the translation rules,
integration tests for the source connector configuration with Debezium’s Testcontainers module, Spring Boot tests for
the consumers that apply change events to the new model (including duplicate and out-of-order delivery), and a test
that runs the connector in-process with the Debezium Engine. It complements
Testing Messaging in Spring Boot, which covers
@ServiceConnection, Kafka test containers and Awaitility in general.
Checked on 2026-11-09 against Debezium 3.7.1.Final (io.debezium:debezium-testing-testcontainers:3.7.1.Final and the
quay.io/debezium/connect:3.7.1.Final image), Spring Boot 4.1.2 with Spring for Apache Kafka, Testcontainers 2.0.5,
the apache/kafka:4.3.1 and postgres:18 images, Java 21 and Maven 3.9. Every test on this page was run on 2026-11-09
with Docker in a throw-away Maven project, with mvn verify, and passed: the unit test class (6 tests), the connector
integration test, the three Spring Boot consumer tests and the Engine test. The run used the code exactly as shown:
the connector and Engine tests with the JSON converters' schemas enabled, and the consumer tests with the
schema-wrapped LegacyEvents fixtures (string NUMBER values, transaction metadata) against the bookshop classes of
Listening to Events in Applications. The project
and its containers were deleted afterwards.
What to test, and where
A CDC pipeline can be wrong in four different places, and each needs a different kind of test:
| Level | What it proves | Runs with | Time |
|---|---|---|---|
Translation rules (unit) |
Each legacy code, flag and type maps to the right value of the new model, and unknown values are rejected. |
JUnit only |
Milliseconds |
Consumers (integration) |
Change events, as the source connector writes them, produce the right rows in the new database, also when an event is delivered twice or out of order. |
Spring Boot test, Kafka and PostgreSQL containers |
Seconds |
Source connector (integration) |
The connector configuration starts, captures the intended tables, produces the expected topic names and envelope, and applies column filters and masks. |
Debezium Testcontainers module: Kafka, Kafka Connect and the database |
Tens of seconds |
Whole pipeline (end to end) |
Legacy database, connectors, sinks and application together, followed by reconciliation. |
The Compose stack of the worked example |
Minutes |
Most tests belong at the bottom: they are fast and pinpoint the broken rule. The connector tests are fewer, one per connector configuration, and they run whenever the configuration changes. The end-to-end run is described on Worked Example: Oracle to PostgreSQL and the checks that follow it on Verification & Reconciliation.
The test project
The tests live in the bookshop Spring Boot application. Unit tests run with Surefire (*Test), and the container
tests run with Failsafe (*IT) in the verify phase, so that mvn test stays fast and needs no Docker.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.2</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>bookshop</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<java.version>21</java.version>
<version.debezium>3.7.1.Final</version.debezium>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jackson</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Tests -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<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>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-kafka</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-testing-testcontainers</artifactId>
<version>${version.debezium}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-embedded</artifactId>
<version>${version.debezium}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-connector-postgres</artifactId>
<version>${version.debezium}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Points to note about the dependencies:
-
debezium-testing-testcontainers3.7.1.Final is built on Testcontainers 2, the same major version that Spring Boot 4.1 manages, so the versions line up without overrides. Testcontainers 2 renamed its modules (testcontainers-kafka,testcontainers-postgresql) and moved the container classes to new packages (org.testcontainers.kafka.KafkaContainer,org.testcontainers.postgresql.PostgreSQLContainer). -
The Debezium module brings Jackson 2 (
com.fasterxml.jackson) for its REST client. Spring Boot 4 uses Jackson 3 (tools.jackson). Both live side by side because their packages differ; the test code uses Jackson 3. -
debezium-embeddedanddebezium-connector-postgresare needed only for the Engine test, and only in the test scope. The connector integration test runs the connectors inside the Connect container, not on the test classpath. -
The official documentation labels the Testcontainers integration as incubating: its API can change between releases.
Unit tests for the translation rules
The anti-corruption layer is mostly small, pure functions: legacy codes to new enumerations, 'Y'/'N' flags to
booleans, Oracle DATE values to date and timestamptz. They need no container, and they should cover every legacy
value that exists in production, which the legacy team can usually list with a SELECT DISTINCT.
package com.example.bookshop.migration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
/** The translation rules of the anti-corruption layer, without Kafka, Debezium or a database. */
class LegacyCodesTest {
@ParameterizedTest
@CsvSource({"NW, NEW", "PD, PAID", "SH, SHIPPED", "CN, CANCELLED"})
void mapsEveryLegacyOrderStatus(String legacy, String expected) {
assertThat(LegacyCodes.orderStatus(legacy)).isEqualTo(expected);
}
@Test
void mapsTheActiveFlag() {
assertThat(LegacyCodes.activeFlag("Y")).isTrue();
assertThat(LegacyCodes.activeFlag("N")).isFalse();
assertThat(LegacyCodes.activeFlag(null)).isNull();
}
@Test
void rejectsAnUnknownCodeInsteadOfGuessing() {
assertThatThrownBy(() -> LegacyCodes.customerStatus("X"))
.isInstanceOf(UnsupportedLegacyValueException.class);
}
}
Reference: JUnit User Guide (parameterized tests)
The last test matters as much as the others. A translator that maps an unknown status to a default value hides a
data problem until reconciliation; one that throws sends the event to the dead-letter topic, where it is visible.
LegacyCodes and UnsupportedLegacyValueException are explained on
Listening to Events in Applications.
Testing the source connector with DebeziumContainer
The Debezium Testcontainers module starts a real Kafka Connect worker from the Debezium image, so the test exercises exactly the connector code and the configuration that production uses. The module provides:
-
DebeziumContainer, aGenericContainerfor thequay.io/debezium/connectimage. It waits until the REST API answers, sets the worker’s group and storage topics, and disablesschemas.enableon the worker’s JSON converters (the connector test below turns them back on in the connector configuration, as Bookshop needs them). Its methods call the Connect REST API:registerConnector,deleteConnector,getConnectorState,ensureConnectorTaskState,getConnectorConfigProperty,pauseConnector,resumeConnector, and with JMX enabled (enableJMX())waitForStreamingRunning. -
ConnectorConfiguration, a builder for the connector configuration.forJdbcContainerfills in the connector class (from the JDBC driver of the container),database.hostname,database.port,database.user,database.passwordanddatabase.dbname;withadds or overrides any property.
There is one difference from the official example. In 3.7.1 DebeziumContainer.withKafka(...) accepts only a Strimzi
StrimziKafkaCluster, not a Testcontainers KafkaContainer as the documentation page shows. With the
KafkaContainer that Spring Boot’s @ServiceConnection supports, add a listener that other containers can reach
(withListener("kafka:9095")) and pass it to the Connect container as BOOTSTRAP_SERVERS.
A PostgreSQL stand-in for the legacy schema
Testing the real Oracle connector needs an Oracle container prepared for LogMiner: archive logging, supplemental
logging, the common user C##DBZUSER and a few minutes of start-up
(Oracle Connector). That belongs in a nightly job or
the end-to-end run. For the tests that run on every change, a PostgreSQL 18 container can stand in for the legacy
schema, as long as it produces the same topic names and the same event shapes:
-
Quoted upper-case identifiers (
"BOOKSHOP"."BOOK","BOOK_ID") give the topiclegacy.BOOKSHOP.BOOKand the field namesBOOK_ID,PRICEand so on, exactly as the Oracle connector writes them. -
timestamp(0)columns are emitted asio.debezium.time.Timestamp(milliseconds since the epoch), which is what the Oracle connector emits forDATE. -
REPLICA IDENTITY FULLgives fullbeforeimages for updates and deletes, like all-column supplemental logging on Oracle. -
decimal.handling.mode=stringgives prices as strings such as"19.90"on both connectors. The ids arenumeric(10)rather thanbigintfor the same reason: like OracleNUMBER(10)with the canonicaldecimal.handling.mode=string, they arrive as strings ("BOOK_ID":"42"). -
The connector configuration sets the JSON converters with schemas enabled, as
bookshop-oracle-sourcedoes, so every key and value is a{"schema":...,"payload":...}document.
What the stand-in cannot test is everything specific to LogMiner: SCN offsets, transaction buffering, mining
strategies, the source block fields scn and commit_scn. Keep those for the Oracle tests.
-- PostgreSQL stand-in for the legacy Oracle BOOKSHOP schema: quoted upper-case names keep the
-- topic names (legacy.BOOKSHOP.BOOK) and the field names (BOOK_ID, PRICE...) of the Oracle pipeline,
-- and numeric(10) ids arrive as strings ("42") with decimal.handling.mode=string, like Oracle NUMBER(10).
CREATE SCHEMA "BOOKSHOP";
CREATE TABLE "BOOKSHOP"."BOOK" (
"BOOK_ID" numeric(10) PRIMARY KEY,
"ISBN" varchar(13),
"TITLE" varchar(200),
"AUTHOR_ID" numeric(10),
"PRICE" numeric(10,2),
"CURRENCY" char(3),
"PUBLISHED" timestamp(0),
"ACTIVE_FLG" char(1),
"SUPPLIER_ID" numeric(10),
"LAST_UPD" timestamp(0)
);
CREATE TABLE "BOOKSHOP"."CUSTOMER" (
"CUST_ID" numeric(10) PRIMARY KEY,
"CUST_NAME" varchar(200),
"EMAIL" varchar(320),
"STATUS_CD" char(1),
"CREATED_DT" timestamp(0)
);
-- Full before images for updates and deletes, as Oracle all-column supplemental logging gives
ALTER TABLE "BOOKSHOP"."BOOK" REPLICA IDENTITY FULL;
ALTER TABLE "BOOKSHOP"."CUSTOMER" REPLICA IDENTITY FULL;
INSERT INTO "BOOKSHOP"."BOOK" VALUES
(42, '9780000000420', 'Strangler Figs', 5, 19.90, 'EUR', '2024-03-01 00:00:00', 'Y', 3, '2026-11-08 10:00:00');
INSERT INTO "BOOKSHOP"."CUSTOMER" VALUES
(7, 'Ada Reader', 'ada.reader@example.com', 'A', '2025-01-15 09:30:00');
Reference: Debezium — PostgreSQL replica identity and PostgreSQL temporal types
The connector test
The test starts Kafka, the legacy database and Kafka Connect on one Docker network, registers a PostgreSQL source
connector with the Bookshop topic prefix, and then checks the snapshot, an update and a delete. It also checks
column.mask.hash.v2 on EMAIL, so the pseudonymisation rule from
Security & Data Protection is part of the build.
package com.example.bookshop.migration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Stream;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.Network;
import org.testcontainers.kafka.KafkaContainer;
import org.testcontainers.lifecycle.Startables;
import org.testcontainers.postgresql.PostgreSQLContainer;
import org.testcontainers.utility.MountableFile;
import io.debezium.testing.testcontainers.Connector;
import io.debezium.testing.testcontainers.ConnectorConfiguration;
import io.debezium.testing.testcontainers.DebeziumContainer;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/**
* Checks the source side of the pipeline: the connector configuration, the topic names, the event
* envelope and the column masking, against a real Kafka Connect worker running Debezium 3.7.1.Final.
*/
class LegacySourceConnectorIT {
private static final String SALT = "bookshop-test-salt";
private static final Network network = Network.newNetwork();
private static final KafkaContainer kafka = new KafkaContainer("apache/kafka:4.3.1")
.withNetwork(network)
.withListener("kafka:9095"); // listener for other containers
private static final PostgreSQLContainer legacyDb = new PostgreSQLContainer("postgres:18")
.withNetwork(network)
.withNetworkAliases("legacy-db")
.withCommand("postgres", "-c", "wal_level=logical") // logical decoding
.withCopyFileToContainer(MountableFile.forClasspathResource("legacy-bookshop-postgres.sql"),
"/docker-entrypoint-initdb.d/01-legacy-bookshop.sql");
private static final DebeziumContainer connect = new DebeziumContainer("quay.io/debezium/connect:3.7.1.Final")
.withNetwork(network)
.withEnv("BOOTSTRAP_SERVERS", "kafka:9095") // the listener above
.dependsOn(kafka, legacyDb);
private final JsonMapper json = JsonMapper.builder().build();
@BeforeAll
static void startContainers() {
Startables.deepStart(Stream.of(kafka, legacyDb, connect)).join();
}
@AfterAll
static void stopContainers() {
connect.stop();
legacyDb.stop();
kafka.stop();
network.close();
}
@Test
void capturesSnapshotUpdatesAndDeletesWithMaskedEmail() throws Exception {
// Connector class, user, password and database name come from the container
ConnectorConfiguration config = ConnectorConfiguration.forJdbcContainer(legacyDb)
.with("database.hostname", "legacy-db")
.with("database.port", 5432)
.with("topic.prefix", "legacy")
.with("plugin.name", "pgoutput")
.with("slot.name", "bookshop_legacy_it")
.with("publication.name", "bookshop_legacy_it_pub")
.with("publication.autocreate.mode", "filtered")
.with("table.include.list", "BOOKSHOP.BOOK,BOOKSHOP.CUSTOMER")
.with("snapshot.mode", "initial")
.with("decimal.handling.mode", "string")
// The canonical wire format: JSON with embedded schemas (DebeziumContainer turns them off)
.with("key.converter", "org.apache.kafka.connect.json.JsonConverter")
.with("key.converter.schemas.enable", "true")
.with("value.converter", "org.apache.kafka.connect.json.JsonConverter")
.with("value.converter.schemas.enable", "true")
.with("column.mask.hash.v2.SHA-256.with.salt." + SALT, "BOOKSHOP.CUSTOMER.EMAIL");
connect.registerConnector("bookshop-legacy-source-it", config);
connect.ensureConnectorTaskState("bookshop-legacy-source-it", 0, Connector.State.RUNNING);
try (KafkaConsumer<String, String> consumer = consumer()) {
consumer.subscribe(List.of("legacy.BOOKSHOP.BOOK", "legacy.BOOKSHOP.CUSTOMER"));
// Snapshot: one read event per existing row
List<ConsumerRecord<String, String>> snapshot = drain(consumer, 2);
JsonNode book = value(snapshot, "legacy.BOOKSHOP.BOOK");
assertThat(book.get("op").asString()).isEqualTo("r");
assertThat(book.at("/after/BOOK_ID").asString()).isEqualTo("42"); // NUMBER as a string
assertThat(book.at("/after/PRICE").asString()).isEqualTo("19.90");
assertThat(book.at("/after/PUBLISHED").asLong()).isEqualTo(1709251200000L); // io.debezium.time.Timestamp
JsonNode customer = value(snapshot, "legacy.BOOKSHOP.CUSTOMER");
assertThat(customer.at("/after/EMAIL").asString())
.isEqualTo(sha256Hex(SALT + "ada.reader@example.com"))
.doesNotContain("@");
// Streaming: an update and a delete in the legacy database
try (Connection connection = DriverManager.getConnection(legacyDb.getJdbcUrl(),
legacyDb.getUsername(), legacyDb.getPassword());
Statement statement = connection.createStatement()) {
statement.execute("UPDATE \"BOOKSHOP\".\"BOOK\" SET \"PRICE\" = 17.50 WHERE \"BOOK_ID\" = 42");
statement.execute("DELETE FROM \"BOOKSHOP\".\"BOOK\" WHERE \"BOOK_ID\" = 42");
}
List<ConsumerRecord<String, String>> changes = drain(consumer, 3);
JsonNode update = payload(changes.get(0).value());
assertThat(update.get("op").asString()).isEqualTo("u");
assertThat(update.at("/before/PRICE").asString()).isEqualTo("19.90");
assertThat(update.at("/after/PRICE").asString()).isEqualTo("17.50");
assertThat(update.at("/source/table").asString()).isEqualTo("BOOK");
JsonNode delete = payload(changes.get(1).value());
assertThat(delete.get("op").asString()).isEqualTo("d");
assertThat(delete.at("/before/BOOK_ID").asString()).isEqualTo("42"); // NUMBER as a string
assertThat(delete.get("after").isNull()).isTrue();
ConsumerRecord<String, String> tombstone = changes.get(2); // follows the delete event
assertThat(tombstone.value()).isNull();
assertThat(payload(tombstone.key()).get("BOOK_ID").asString()).isEqualTo("42");
}
finally {
connect.deleteConnector("bookshop-legacy-source-it");
}
}
private KafkaConsumer<String, String> consumer() {
return new KafkaConsumer<>(Map.of(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers(),
ConsumerConfig.GROUP_ID_CONFIG, "it-" + UUID.randomUUID(),
ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"),
new StringDeserializer(), new StringDeserializer());
}
private static List<ConsumerRecord<String, String>> drain(KafkaConsumer<String, String> consumer, int expected) {
List<ConsumerRecord<String, String>> records = new ArrayList<>();
await().atMost(Duration.ofSeconds(60)).until(() -> {
consumer.poll(Duration.ofMillis(200)).forEach(records::add);
return records.size() >= expected;
});
assertThat(records).hasSize(expected);
return records;
}
private JsonNode value(List<ConsumerRecord<String, String>> records, String topic) {
return records.stream()
.filter(r -> r.topic().equals(topic))
.findFirst()
.map(r -> payload(r.value()))
.orElseThrow();
}
/** Schemas are enabled: every key and value is {"schema":...,"payload":...}. */
private JsonNode payload(String message) {
JsonNode node = json.readTree(message);
assertThat(node.has("schema")).isTrue();
return node.get("payload");
}
/** Hashing strategy v2: the hash of the salt followed by the value, as lower-case hex. */
private static String sha256Hex(String saltAndValue) throws Exception {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(saltAndValue.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
}
}
What each part checks:
-
ensureConnectorTaskState(..., RUNNING)fails fast when the configuration is invalid, for example a misspelt property value. Without it the test would wait for records until the timeout. -
The snapshot assertions pin the topic names, the
opcodes and the value encodings ("19.90"for the price,1709251200000for thePUBLISHEDtimestamp of 2024-03-01). A change ofdecimal.handling.modeortime.precision.modebreaks this test, not the consumers in production. -
The masked e-mail is compared with a hash computed in the test: the version 2 strategy is the SHA-256 digest of the salt followed by the value, as lower-case hexadecimal. The test passed with Debezium 3.7.1.Final, which confirms the formula.
-
The update carries both images, which is what the translators' out-of-order guard and the reconciliation reports rely on.
-
The delete is followed by a tombstone with the same key. A sink with
delete.enabled=trueand compacted topics depend on it. -
The
finallyblock deletes the connector, which also lets the next test reuse the containers. The replication slot stays in the database, which does not matter for a container that is thrown away.
The first run pulls the images (the Connect image is large) and took about three minutes; later runs took about 20 seconds for this class. The Kafka consumer uses a random group id, so each test reads the topics from the beginning.
Testing the consumers with Spring Boot
The translators of the anti-corruption layer are Kafka listeners that write to PostgreSQL. They do not care whether an event came from Debezium or from a test, so the fastest realistic test sends recorded change events to Kafka and checks the rows of the new model. There is no Debezium and no legacy database in this test, which makes it fast and, more importantly, makes it possible to produce situations that are hard to provoke with a real connector: duplicates after a crash, events in an unexpected order, values that should never occur.
@ServiceConnection on the two containers wires spring.kafka.bootstrap-servers and the data source automatically. The
schema of the new database comes from the same SQL (or schema migrations) as production.
package com.example.bookshop.migration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
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.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.kafka.core.KafkaTemplate;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.kafka.KafkaContainer;
import org.testcontainers.postgresql.PostgreSQLContainer;
/**
* Checks the anti-corruption layer: recorded Oracle change events go in through Kafka, rows of the new
* model come out in PostgreSQL. No Debezium and no Oracle are needed for this level of test.
*/
@Testcontainers
@SpringBootTest(properties = {
"BOOKSHOP_DB_PASSWORD=unused", // the real password comes from @ServiceConnection
"bookshop.legacy-sync.concurrency=1"
})
class LegacyBookTranslatorIT {
@Container
@ServiceConnection
static KafkaContainer kafka = new KafkaContainer("apache/kafka:4.3.1");
@Container
@ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18")
.withDatabaseName("bookshop")
.withInitScript("bookshop-schema.sql");
@Autowired
KafkaTemplate<String, String> kafkaTemplate;
@Autowired
JdbcClient jdbc;
@Test
void mapsLegacyBookToNewModel() {
send("legacy.BOOKSHOP.AUTHOR", LegacyEvents.authorKey(5), LegacyEvents.author("r", "4000", 5, "Ada Writer"));
send("legacy.BOOKSHOP.BOOK", LegacyEvents.bookKey(42),
LegacyEvents.book("r", "5000", 42, "Strangler Figs", "Y", LegacyEvents.NOV_01_10H));
await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
var book = jdbc.sql("SELECT title, price, currency, published_on, active FROM book WHERE id = 42")
.query((rs, n) -> new Object[] {rs.getString(1), rs.getBigDecimal(2), rs.getString(3),
rs.getObject(4, LocalDate.class), rs.getBoolean(5)})
.single();
assertThat(book).containsExactly("Strangler Figs", new BigDecimal("19.90"), "EUR",
LocalDate.of(2024, 3, 1), true); // 'Y' -> true, DATE -> date
assertThat(jdbc.sql("SELECT author_id FROM book_author WHERE book_id = 42")
.query(Long.class).list()).containsExactly(5L); // one AUTHOR_ID -> link table
});
}
@Test
void appliesARedeliveredEventOnce() {
String update = LegacyEvents.book("u", "6000", 142, "Strangler Figs, 2nd edition", "N",
LegacyEvents.NOV_09_10H);
send("legacy.BOOKSHOP.BOOK", LegacyEvents.bookKey(142), update);
send("legacy.BOOKSHOP.BOOK", LegacyEvents.bookKey(142), update); // the same change, redelivered
sendMarkerAndWait(1142);
assertThat(jdbc.sql("""
SELECT count(*) FROM processed_change
WHERE source_table = 'BOOKSHOP.BOOK' AND source_position LIKE 'tx:6001:%'
""").query(Long.class).single()).isEqualTo(1L);
assertThat(jdbc.sql("SELECT active FROM book WHERE id = 142").query(Boolean.class).single()).isFalse();
}
@Test
void ignoresAnOlderVersionThatArrivesLate() {
send("legacy.BOOKSHOP.BOOK", LegacyEvents.bookKey(242),
LegacyEvents.book("u", "7000", 242, "Current title", "Y", LegacyEvents.NOV_09_10H));
send("legacy.BOOKSHOP.BOOK", LegacyEvents.bookKey(242),
LegacyEvents.book("u", "6500", 242, "Stale title", "Y", LegacyEvents.NOV_01_10H));
sendMarkerAndWait(1242);
assertThat(jdbc.sql("SELECT title FROM book WHERE id = 242").query(String.class).single())
.isEqualTo("Current title");
}
private void send(String topic, String key, String value) {
kafkaTemplate.send(topic, key, value).join();
}
/** A later event on the same single-partition topic: once it is applied, everything before it was too. */
private void sendMarkerAndWait(long bookId) {
send("legacy.BOOKSHOP.BOOK", LegacyEvents.bookKey(bookId),
LegacyEvents.book("c", String.valueOf(90000 + bookId), bookId, "Marker", "Y", LegacyEvents.NOV_09_10H));
await().atMost(Duration.ofSeconds(30)).until(() ->
jdbc.sql("SELECT count(*) FROM book WHERE id = :id").param("id", bookId).query(Long.class).single() == 1L);
}
}
The events are built from templates in the shape that bookshop-oracle-source writes: the JSON converter with
schemas enabled, so key and value are {"schema":...,"payload":...} documents, decimal.handling.mode=string, so
every NUMBER including BOOK_ID is a string, and provide.transaction.metadata=true, so streamed events carry the
transaction block that the consumers use as their idempotency key. The schema part of the fixtures is shortened to
an empty field list, because the consumers read only the payload. In a real project, record a few events of each
table from the lab pipeline (with kafka-console-consumer.sh --formatter-property print.key=true), pseudonymise them,
and keep them next to the tests. When the connector configuration changes, record them again; a failing consumer test then shows exactly which
consumer depends on the changed shape.
package com.example.bookshop.migration;
/**
* Change events in the shape that the bookshop-oracle-source connector writes: the JSON converter with
* schemas enabled ({"schema":...,"payload":...}), decimal.handling.mode=string (every NUMBER, keys
* included, is a string) and provide.transaction.metadata=true. The schema part is shortened, because
* the consumers read only the payload. Record real events from the pipeline and keep them here.
*/
final class LegacyEvents {
/** Oracle DATE values as io.debezium.time.Timestamp (epoch milliseconds of the wall-clock time). */
static final long NOV_01_10H = 1793527200000L; // 2026-11-01 10:00
static final long NOV_09_10H = 1794218400000L; // 2026-11-09 10:00
static final long MAR_01_00H = 1709251200000L; // 2024-03-01 00:00
private LegacyEvents() {
}
static String bookKey(long bookId) {
return withSchema("legacy.BOOKSHOP.BOOK.Key", "{\"BOOK_ID\":\"%d\"}".formatted(bookId));
}
static String authorKey(long authorId) {
return withSchema("legacy.BOOKSHOP.AUTHOR.Key", "{\"AUTHOR_ID\":\"%d\"}".formatted(authorId));
}
static String book(String op, String scn, long bookId, String title, String activeFlg, long lastUpd) {
String row = """
{"BOOK_ID":"%d","ISBN":"9780000000420","TITLE":"%s","AUTHOR_ID":"5","PRICE":"19.90",\
"CURRENCY":"EUR","PUBLISHED":%d,"ACTIVE_FLG":"%s","SUPPLIER_ID":"3","LAST_UPD":%d}"""
.formatted(bookId, title, MAR_01_00H, activeFlg, lastUpd);
return envelope(op, "BOOK", scn, "r".equals(op) || "c".equals(op) ? "null" : row, row);
}
static String author(String op, String scn, long authorId, String fullName) {
String row = "{\"AUTHOR_ID\":\"%d\",\"FULL_NAME\":\"%s\"}".formatted(authorId, fullName);
return envelope(op, "AUTHOR", scn, "null", row);
}
private static String envelope(String op, String table, String scn, String before, String after) {
boolean snapshot = "r".equals(op);
// Snapshot reads carry no transaction; a streamed change gets a transaction id per SCN in these fixtures
String txId = snapshot ? "null" : "\"0a001b00%08x\"".formatted(Long.parseLong(scn));
String commitScn = snapshot ? "null" : "\"" + (Long.parseLong(scn) + 1) + "\"";
String transaction = snapshot ? "null"
: "{\"id\":%s,\"total_order\":1,\"data_collection_order\":1}".formatted(txId);
String payload = """
{"before":%s,"after":%s,\
"source":{"version":"3.7.1.Final","connector":"oracle","name":"legacy","ts_ms":1794219300000,\
"snapshot":"%s","db":"FREEPDB1","schema":"BOOKSHOP","table":"%s",\
"txId":%s,"scn":"%s","commit_scn":%s},\
"op":"%s","ts_ms":1794219301000,"transaction":%s}"""
.formatted(before, after, snapshot ? "true" : "false", table, txId, scn, commitScn, op, transaction);
return withSchema("legacy.BOOKSHOP.%s.Envelope".formatted(table), payload);
}
/** The JSON converter with schemas enabled; the real schema lists every field with its type. */
private static String withSchema(String name, String payload) {
return """
{"schema":{"type":"struct","name":"%s","optional":false,"fields":[]},"payload":%s}"""
.formatted(name, payload);
}
}
The three tests cover the properties that matter most in a migration:
-
Mapping. A snapshot
revent forBOOK42 andAUTHOR5 produces abookrow with the translated values ('Y'becomestrue, theDATEbecomes2024-03-01in the legacy time zone) and thebook_authorrow that replaces the legacy singleAUTHOR_ID. -
Idempotent replay. The same update is sent twice, as Kafka Connect does after a worker crash. The
processed_changetable holds one row for its source position, so the second delivery was recognised and skipped. -
Out-of-order delivery. An older version of a row (by
LAST_UPD) arrives after a newer one, which can happen when a snapshot and streaming overlap or after a replay. The newer title stays.
Asserting that something did not happen needs care: waiting a fixed time is slow and flaky. The tests send a marker event to the same single-partition topic after the events under test, and wait until the marker is applied. Because a partition is consumed in order, everything before the marker has been processed by then. With several partitions, send the marker with the same key as the events under test.
Testing with the Debezium Engine
When the migration uses the Debezium Engine instead of Kafka Connect (Debezium Engine (Embedded)), the connector runs inside the test JVM. No Kafka and no Connect container are needed; the offsets can live in memory.
package com.example.bookshop.migration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.time.Duration;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.postgresql.PostgreSQLContainer;
import org.testcontainers.utility.MountableFile;
import io.debezium.engine.ChangeEvent;
import io.debezium.engine.DebeziumEngine;
import io.debezium.engine.format.Json;
/** The same source configuration, run in-process by the Debezium Engine: no Kafka, no Connect worker. */
@Testcontainers
class LegacyEngineIT {
@Container
static PostgreSQLContainer legacyDb = new PostgreSQLContainer("postgres:18")
.withCommand("postgres", "-c", "wal_level=logical")
.withCopyFileToContainer(MountableFile.forClasspathResource("legacy-bookshop-postgres.sql"),
"/docker-entrypoint-initdb.d/01-legacy-bookshop.sql");
@Test
void streamsLegacyChangesWithoutKafka() throws Exception {
Properties props = new Properties();
props.setProperty("name", "bookshop-legacy-engine-it");
props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector");
props.setProperty("offset.storage", "org.apache.kafka.connect.storage.MemoryOffsetBackingStore");
props.setProperty("offset.flush.interval.ms", "0");
props.setProperty("database.hostname", legacyDb.getHost());
props.setProperty("database.port", String.valueOf(legacyDb.getMappedPort(5432)));
props.setProperty("database.user", legacyDb.getUsername());
props.setProperty("database.password", legacyDb.getPassword());
props.setProperty("database.dbname", legacyDb.getDatabaseName());
props.setProperty("topic.prefix", "legacy");
props.setProperty("plugin.name", "pgoutput");
props.setProperty("slot.name", "bookshop_engine_it");
props.setProperty("publication.autocreate.mode", "filtered");
props.setProperty("table.include.list", "BOOKSHOP.BOOK");
props.setProperty("decimal.handling.mode", "string");
props.setProperty("key.converter.schemas.enable", "true"); // as on bookshop-oracle-source
props.setProperty("value.converter.schemas.enable", "true");
List<ChangeEvent<String, String>> events = new CopyOnWriteArrayList<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
try (DebeziumEngine<ChangeEvent<String, String>> engine = DebeziumEngine.create(Json.class)
.using(props)
.notifying(event -> events.add(event))
.build()) {
executor.execute(engine);
await().atMost(Duration.ofSeconds(60)).until(() -> events.size() >= 1); // snapshot of BOOK 42
try (Connection connection = DriverManager.getConnection(legacyDb.getJdbcUrl(),
legacyDb.getUsername(), legacyDb.getPassword());
Statement statement = connection.createStatement()) {
statement.execute("UPDATE \"BOOKSHOP\".\"BOOK\" SET \"ACTIVE_FLG\" = 'N' WHERE \"BOOK_ID\" = 42");
}
await().atMost(Duration.ofSeconds(60)).until(() -> events.size() >= 2);
}
finally {
executor.shutdown();
}
assertThat(events.get(0).destination()).isEqualTo("legacy.BOOKSHOP.BOOK");
assertThat(events.get(0).value()).contains("\"schema\":").contains("\"op\":\"r\"");
assertThat(events.get(1).value()).contains("\"op\":\"u\"").contains("\"ACTIVE_FLG\":\"N\"");
}
}
Reference: Debezium — Debezium Engine
Two details from running it:
-
.notifying(events::add)does not compile:List.addreturns a value, so the method reference matches bothnotifying(Consumer)andnotifying(ChangeConsumer). The lambdaevent -> events.add(event)resolves to theConsumervariant. -
org.apache.kafka.connect.storage.MemoryOffsetBackingStorekeeps the offsets in memory, so every test starts with a snapshot. That is what a test wants; production needs a persistent store.
The Engine test is also the quickest way to check a connector property against a real database while writing the configuration, before the Connect-based test exists.
Testing failures and schema changes
The happy path is the smallest part of what can go wrong. Once the basic tests run, add tests for the situations on Troubleshooting & Failure Recovery. The containers make them reproducible:
-
Connector restart. Pause or delete and re-register the connector between changes (
pauseConnector,resumeConnector), and check that the consumer state is still correct. After a crash Debezium may deliver changes again; the consumer test above covers the effect, a restart test covers the cause. -
Consumer restart. Stop the Spring listener container in the middle of a batch (
KafkaListenerEndpointRegistry), start it again, and compare the new tables with the legacy stand-in. -
Schema changes. Run
ALTER TABLE ... ADD COLUMNon the stand-in while the connector streams, insert a row, and assert that the new field appears in the event and that the consumers ignore or map it. The expected behaviour of each component is on Handling Schema Changes. -
Poison events. Send an event with an unknown code, and assert that it reaches the dead-letter topic (
legacy.BOOKSHOP.BOOK.DLT) and that the following events are still applied. -
Sink configuration. Register the JDBC sink (
bookshop-pg-mirror-sink) in the sameDebeziumContainerwith the PostgreSQL target as a second container, and assert thelegacy_*mirror rows, including deletes. The sink configuration is on JDBC Sink Connector.
These additional tests were not part of the run on 2026-11-09; they reuse the classes above.
Running the tests in CI
-
Docker is required for every
*ITclass. Testcontainers starts its Ryuk container to remove the test containers when the JVM exits, even after a failure. CI runners without Docker can still run the unit tests withmvn test. -
Images. Pin the image tags (
quay.io/debezium/connect:3.7.1.Final,apache/kafka:4.3.1,postgres:18) and keep the Debezium image version equal to the Debezium version of the production Connect cluster. Pre-pull the images in the CI image or cache them, because the Connect image dominates the first run. -
One network per class. The connector test creates its own Docker network and closes it in
@AfterAll. Static containers are shared by the tests of a class; use different connector names, slots and keys per test if a class has several. -
Timeouts. Use Awaitility with a generous upper bound (60 seconds for connector tests) and poll, rather than fixed sleeps. A connector that does not start fails fast with
ensureConnectorTaskState. -
Fixtures and data. Keep test data synthetic. Recorded events from a production pipeline are personal data, as explained on Security & Data Protection.
mvn test # unit tests only, no Docker
mvn verify # unit tests and the Testcontainers integration tests
Reference: Maven Failsafe Plugin
The full mvn verify of the project on this page took about 50 seconds with the images already present, of which
about 20 seconds were the connector test.