Integration Testing with Testcontainers

Overview

When setting up change data capture pipelines with Debezium, it’s a good idea to also have some automated testing in place, in order to make sure that

  • the source database is set up so changes can be streamed off of it

  • your connectors are configured correctly

The Debezium extension for Testcontainers aims at simplying such tests, by running all the required infrastructure (Apache Kafka, Kafka Connect etc.) via Linux containers and making it easily accessible to Java-based tests.

It applies sensible defaults as far as possible (e.g. database credentials for connectors can be obtained from the configured database container), allowing you to focus on the essential logic of your tests.

Getting Started

In order to use Debezium’s Testcontainers integration, add the following dependency to your project:

  1. <dependency>
  2. <groupId>io.debezium</groupId>
  3. <artifactId>debezium-testing-testcontainers</artifactId>
  4. <version>2.4.1.Final</version>
  5. <scope>test</scope>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.testcontainers</groupId>
  9. <artifactId>kafka</artifactId>
  10. <scope>test</scope>
  11. </dependency>
  12. <!-- Add the TC dependency matching your database -->
  13. <dependency>
  14. <groupId>org.testcontainers</groupId>
  15. <artifactId>postgresql</artifactId>
  16. <scope>test</scope>
  17. </dependency>

Depending on your testing strategy, you may also need the JDBC driver of your database and a client for Apache Kafka, so you can insert some test data and assert the corresponding change events in Kafka.

Test Set-Up

When writing an integration test for a Debezium connector configuration, you’ll also need to set up Apache Kafka and a database which should be the source of change events. The existing Testcontainers support for Apache Kafka and databases can be used for that.

Together with Debezium’s DebeziumContainer class, a typical set-up will look like this:

  1. public class DebeziumContainerTest {
  2. private static Network network = Network.newNetwork(); (1)
  3. private static KafkaContainer kafkaContainer = new KafkaContainer()
  4. .withNetwork(network); (2)
  5. public static PostgreSQLContainer<?> postgresContainer =
  6. new PostgreSQLContainer<>(
  7. DockerImageName.parse("quay.io/debezium/postgres:15")
  8. .asCompatibleSubstituteFor("postgres"))
  9. .withNetwork(network)
  10. .withNetworkAliases("postgres"); (3)
  11. public static DebeziumContainer debeziumContainer =
  12. new DebeziumContainer("quay.io/debezium/connect:2.4.1.Final")
  13. .withNetwork(network)
  14. .withKafka(kafkaContainer)
  15. .dependsOn(kafkaContainer); (4)
  16. @BeforeClass
  17. public static void startContainers() { (5)
  18. Startables.deepStart(Stream.of(
  19. kafkaContainer, postgresContainer, debeziumContainer))
  20. .join();
  21. }
  22. }
1Define a Docker network to be used by all the services
2Set up a container for Apache Kafka
3Set up a container for Postgres 15 (using Debezium’s Postgres container image)
4Set up a container for Kafka Connect with Debezium 2.4.1.Final
5Start all three containers

Test Implementation

Having declared all the required containers, you can now register an instance of the Debezium Postgres connector, insert some test data into Postgres and use the Apache Kafka client for reading the expected change event records from the corresponding Kafka topic:

  1. @Test
  2. public void canRegisterPostgreSqlConnector() throws Exception {
  3. try (Connection connection = getConnection(postgresContainer);
  4. Statement statement = connection.createStatement();
  5. KafkaConsumer<String, String> consumer = getConsumer(
  6. kafkaContainer)) {
  7. statement.execute("create schema todo"); (1)
  8. statement.execute("create table todo.Todo (id int8 not null, " +
  9. "title varchar(255), primary key (id))");
  10. statement.execute("alter table todo.Todo replica identity full");
  11. statement.execute("insert into todo.Todo values (1, " +
  12. "'Learn CDC')");
  13. statement.execute("insert into todo.Todo values (2, " +
  14. "'Learn Debezium')");
  15. ConnectorConfiguration connector = ConnectorConfiguration
  16. .forJdbcContainer(postgresContainer)
  17. .with("topic.prefix", "dbserver1");
  18. debeziumContainer.registerConnector("my-connector",
  19. connector); (2)
  20. consumer.subscribe(Arrays.asList("dbserver1.todo.todo"));
  21. List<ConsumerRecord<String, String>> changeEvents =
  22. drain(consumer, 2); (3)
  23. assertThat(JsonPath.<Integer> read(changeEvents.get(0).key(),
  24. "$.id")).isEqualTo(1);
  25. assertThat(JsonPath.<String> read(changeEvents.get(0).value(),
  26. "$.op")).isEqualTo("r");
  27. assertThat(JsonPath.<String> read(changeEvents.get(0).value(),
  28. "$.after.title")).isEqualTo("Learn CDC");
  29. assertThat(JsonPath.<Integer> read(changeEvents.get(1).key(),
  30. "$.id")).isEqualTo(2);
  31. assertThat(JsonPath.<String> read(changeEvents.get(1).value(),
  32. "$.op")).isEqualTo("r");
  33. assertThat(JsonPath.<String> read(changeEvents.get(1).value(),
  34. "$.after.title")).isEqualTo("Learn Debezium");
  35. consumer.unsubscribe();
  36. }
  37. }
  38. // Helper methods below
  39. private Connection getConnection(
  40. PostgreSQLContainer<?> postgresContainer)
  41. throws SQLException {
  42. return DriverManager.getConnection(postgresContainer.getJdbcUrl(),
  43. postgresContainer.getUsername(),
  44. postgresContainer.getPassword());
  45. }
  46. private KafkaConsumer<String, String> getConsumer(
  47. KafkaContainer kafkaContainer) {
  48. return new KafkaConsumer<>(
  49. Map.of(
  50. ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
  51. kafkaContainer.getBootstrapServers(),
  52. ConsumerConfig.GROUP_ID_CONFIG,
  53. "tc-" + UUID.randomUUID(),
  54. ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,
  55. "earliest"),
  56. new StringDeserializer(),
  57. new StringDeserializer());
  58. }
  59. private List<ConsumerRecord<String, String>> drain(
  60. KafkaConsumer<String, String> consumer,
  61. int expectedRecordCount) {
  62. List<ConsumerRecord<String, String>> allRecords = new ArrayList<>();
  63. Unreliables.retryUntilTrue(10, TimeUnit.SECONDS, () -> {
  64. consumer.poll(Duration.ofMillis(50))
  65. .iterator()
  66. .forEachRemaining(allRecords::add);
  67. return allRecords.size() == expectedRecordCount;
  68. });
  69. return allRecords;
  70. }
1Create a table in the Postgres database and insert two records
2Register an instance of the Debezium Postgres connector; the connector type as well as properties such as database host, database name, user etc. are derived from the database container
3Read two records from the change event topic in Kafka and assert their attributes