Video in progress
When integration-testing a Kafka listener, how do you choose between EmbeddedKafka and Kafka in Testcontainers, and what do you watch for?
@EmbeddedKafka is fast and needs no Docker, but it's a broker inside the JVM, so its settings differ from prod. Testcontainers gives you a real broker image. Either way, since the listener works asynchronously, you wait for the result with Awaitility and check offset, retry and DLT behavior.
📖 Answer
A typical test:
@SpringBootTest
@Testcontainers
class PaymentEventsIT {
@Container @ServiceConnection
static KafkaContainer kafka = new KafkaContainer("apache/kafka-native:3.8.0");
@Autowired KafkaTemplate<String, String> template;
@Autowired PaymentRepository payments;
@Test
void tolov_hodisasi_qayta_ishlanadi() {
template.send("payments", "order-42", "{\"orderId\":42,\"amount\":150000}");
await().atMost(Duration.ofSeconds(15))
.untilAsserted(() -> assertTrue(payments.existsByOrderId(42L)));
}
}
(org.testcontainers.kafka.KafkaContainer is the new class in Testcontainers 1.20+; the old one worked with confluentinc/cp-kafka.)
Things to watch:
auto.offset.reset: if the consumer joins after the test starts and it's set tolatest, it won't see the message that was sent. Useearliestin tests;- each test should work with its own topic or unique keys, otherwise one test's messages land in the next one;
- the failure scenario: send invalid JSON and use a separate consumer to check that after the retries it lands in the
payments.DLTtopic. This is the part that breaks most often in prod; - idempotency: send the same message twice and check that the result is only one.
How to choose: for simple serialization and routing, @EmbeddedKafka is enough. For a transactional producer, Schema Registry, or behavior that depends on the broker version, use Testcontainers.
Sign up to mark studied questions and save your progress.