Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

How do you write an integration test for a Spring Boot service that consumes from Kafka and stores records in a database? Compare @EmbeddedKafka with Testcontainers, and show how the test waits for the asynchronous result.

An integration test starts a broker and a database, sends a record with KafkaTemplate, and waits with Awaitility until the row appears, instead of sleeping for a fixed time. @EmbeddedKafka from spring-kafka-test runs a broker inside the test JVM and is quick to set up, while Testcontainers runs a real Kafka image, such as apache/kafka in KRaft mode, which is closer to production and with Spring Boot 3.1 or later needs only @ServiceConnection on the container field. Each test uses its own topic or group id with auto-offset-reset=earliest, and the listener's logic is unit-tested separately.

Why this question is asked

Kafka consumers are asynchronous, which makes them harder to test than a REST endpoint: the test sends a record and the effect happens later, on another thread. Tests written naively either sleep and become slow and flaky, or check too early and fail. Interviewers ask this to see whether we know the standard tools and the few rules that make such tests reliable. In this answer, we will recap the two ways to get a broker in a test, write a full Testcontainers test with a database, show how to wait for the result, look at the settings that prevent missed records, and see where plain unit tests fit.

1A Quick Recap: Two Ways to Get a Broker

@EmbeddedKafka comes with spring-kafka-test. It starts a Kafka broker inside the same JVM as the test, in KRaft mode in recent versions, and exposes its address in the spring.embedded.kafka.brokers property. It needs no Docker and starts in a few seconds, which is pleasant on a laptop and in CI runners without Docker.

Testcontainers starts a real Kafka Docker image, for example apache/kafka, the official Apache image, which runs in KRaft mode without ZooKeeper. It is the same broker software we run in production, with real networking, and the same approach starts the database too. The cost is that Docker must be available and the first start pulls images.

@EmbeddedKafka or Testcontainers
@EmbeddedKafkaTestcontainers
Runs whereinside the test JVMDocker container
Startupseconds, no Dockerseconds after the image is pulled
Closeness to productionsame code, embedded setupreal image, real networking
Boot wiringspring.embedded.kafka.brokers@ServiceConnection on the field
Good forfast tests of Spring Kafka wiringfull service tests with a database

2A Full Test With Testcontainers

Here is a test for a service whose listener reads payments and saves them with a Spring Data repository. Both Kafka and PostgreSQL run as containers, and @ServiceConnection tells Spring Boot to take the connection details, the bootstrap servers and the JDBC URL, straight from the containers.

Java
@SpringBootTest(properties = {
"app.topic=payments-${random.uuid}", // a fresh topic per context
"spring.kafka.consumer.group-id=test-${random.uuid}",
"spring.kafka.consumer.auto-offset-reset=earliest"
})
@Testcontainers
class PaymentListenerIT {
@Container @ServiceConnection
static KafkaContainer kafka = new KafkaContainer("apache/kafka:4.1.0"); // org.testcontainers.kafka
@Container @ServiceConnection
static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17");
@Autowired KafkaTemplate<String, String> template;
@Autowired PaymentRepository payments;
@Value("${app.topic}") String topic;
@Test
void storesPayment() {
template.send(topic, "p-1", "{\"id\":\"p-1\",\"amountCents\":500}");
await().atMost(Duration.ofSeconds(10))
.untilAsserted(() -> assertThat(payments.findById("p-1"))
.hasValueSatisfying(p -> assertThat(p.amountCents()).isEqualTo(500)));
}
}

Notice that the listener reads its topic from app.topic, so the test can give it a unique name. The KafkaContainer class here is the one from the org.testcontainers.kafka package, which supports the apache/kafka image; Testcontainers also has an older Confluent-based class, so check your version and imports. The containers are static, so they start once for the test class.

3Waiting for the Asynchronous Result

The send returns immediately, and the listener processes the record a moment later on its own thread. The tempting fix is Thread.sleep(5000) before asserting, but that is always slow, and on a busy CI machine five seconds is sometimes not enough. Awaitility solves both problems. await().atMost(Duration.ofSeconds(10)).untilAsserted(...) runs the assertion repeatedly, every 100 ms by default, until it passes or the time runs out. On a fast machine the test finishes as soon as the row appears, perhaps after 300 ms, and on a slow one it still has ten seconds before it fails with the last assertion error, which tells us exactly what was missing.

Step throughWhat the test waits for
TestKafkaListenerDatabase
send payments-1234, key p-1
findById(p-1): empty, retry in 100 ms
poll() returns the record
save payment
findById(p-1): found, amount 500

5 messages in order. Play them, or step through them one at a time.

Awaitility repeats the assertion until it passes, instead of guessing a sleep.

4Settings That Prevent Missed and Stray Records

Two details decide whether the consumer sees the record at all. First, a brand-new consumer group starts reading at the end of the topic by default, because auto.offset.reset is latest. If the test sends before the consumer has received its partitions, which is easy because both start at almost the same time, the record is behind the starting point and never read. Setting auto-offset-reset=earliest for tests makes a new group start at the beginning, so the race no longer matters.

Second, tests must not share data. If several tests use the same topic and group id, one test can read the record another test sent, or start from an offset an earlier test committed. A unique topic name or group id per test class, as with the random values above, keeps each test's records to itself. Where a shared topic is unavoidable, we use unique keys per test and assert only on our own key.

5Keeping Listener Logic in Unit Tests

The integration test proves the wiring: deserialization, the listener annotation, the transaction and the database mapping. It does not need to cover every business rule. The listener method is an ordinary method, so we call it directly in a plain JUnit test with a mocked or in-memory repository, and test validation, error cases and edge values in milliseconds. A handful of integration tests and many unit tests is a much faster suite than dozens of container tests.

Java
@Test
void rejectsNegativeAmount() {
var listener = new PaymentListener(new InMemoryPaymentRepository());
assertThatThrownBy(() -> listener.onPayment("{\"id\":\"p-2\",\"amountCents\":-5}"))
.isInstanceOf(InvalidPaymentException.class); // no broker, runs in a few ms
}

6Follow-up questions

When would you use MockProducer and MockConsumer?

They are classes in the Kafka client library that implement the Producer and Consumer interfaces in memory, with no broker. MockProducer records every send so a test can inspect what was sent, and it can be told to complete or fail sends. MockConsumer lets a test add records and assignments by hand. I would use them for code that talks to the raw Kafka client directly, such as a custom polling loop or a small library, where I want fast tests of my own logic. For Spring listener containers they are less useful, because the container builds its own consumers, so there I prefer a real broker.

How do you keep container tests fast across many test classes?

Start the containers once per test run, for example in a shared base class or with singleton containers, and keep the Spring context cacheable by using the same configuration. Then isolate data with unique topics, group ids and keys instead of restarting the broker. Testcontainers' reuse feature can also keep containers between local runs.

7Conclusion

In this answer, we compared @EmbeddedKafka, a broker inside the test JVM that is quick and needs no Docker, with Testcontainers, a real apache/kafka image that is closer to production and connects with @ServiceConnection. We wrote a full test that sends a record with KafkaTemplate and waits for the database row with Awaitility instead of sleeping, gave each test its own topic and group id with auto-offset-reset=earliest so records are neither missed nor shared, and kept the listener's business logic in fast unit tests.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write a Spring Boot test that starts Kafka and the database, sends a record with KafkaTemplate and then waits for the row in the database. For the broker there are two options.

Then, if they want more

EmbeddedKafka from spring-kafka-test runs a broker inside the test JVM; it is fast and needs no Docker. Testcontainers runs a real Kafka image, for example apache/kafka in KRaft mode, which is closer to production, and since Spring Boot 3.1 I just put ServiceConnection on the container field and Boot sets the bootstrap servers. I use the same for PostgreSQL.

For the asynchronous part I never use Thread.sleep; I use Awaitility, something like await at most ten seconds until asserted that the repository finds the payment. It polls the assertion, so the test is fast when things are fast and still tolerant in a slow CI run.

Two settings matter for reliability: a unique topic or group id per test, so tests do not read each other's records or offsets, and auto offset reset earliest, so the consumer does not miss a record sent before it got its partitions.

Finally, I test the listener's business logic separately as plain unit tests, calling the method directly without Kafka, and keep only a few integration tests for the wiring.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3.1
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do you write an integration test for a Spring Boot service that consumes from Kafka...": https://scrivio-interview-library.netlify.app/spring-boot/kafka/897d62a5c1/