Sub topic 14
Testing producers and listeners
This chapter assumes you have followed the earlier chapters. You should have the OrderPublisher, OrderListener, OrderEvent and NewTopic code from the order service. You should also know basic JUnit 5, Mockito and @SpringBootTest. Here you will test that code at three levels, and you will see which kinds of bugs each level can catch.
Choosing a test level
Kafka code fails in ways that mocks cannot show. Examples are a wrong serializer, a missing trusted package, a key that sends events to the wrong partition, or a listener that never joins its group. The usual answer is a small number of fast unit tests plus a few integration tests against a real broker.
| Level | Tool | Catches | Cost |
|---|---|---|---|
| Unit | Mockito, plain JUnit | Wrong topic, wrong key, callback logic | Milliseconds |
| Embedded broker | `@EmbeddedKafka` | Serialization, config, topic wiring, listener behavior | Seconds, runs in the JVM |
| Container | Testcontainers | Everything above, on a real broker image | Seconds to start, needs Docker |
Dependencies
spring-boot-starter-test brings JUnit 5, Mockito, AssertJ and Awaitility. Embedded Kafka needs one more artifact.
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka-test</artifactId>
<scope>test</scope>
</dependency>Spring Boot manages the version, so you do not set one.
Unit testing the publisher
OrderPublisher depends only on KafkaTemplate, so you can mock it. In Spring for Apache Kafka 3.x, send returns a CompletableFuture. The mock must return a future, or the call to whenComplete throws a NullPointerException.
package com.example.orders;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.kafka.core.KafkaTemplate;
@ExtendWith(MockitoExtension.class)
class OrderPublisherTest {
@Mock
KafkaTemplate<String, OrderEvent> kafkaTemplate;
@InjectMocks
OrderPublisher publisher;
@Test
void usesOrderIdAsKey() {
OrderEvent event = new OrderEvent("o-1", 500);
when(kafkaTemplate.send("orders", "o-1", event))
.thenReturn(new CompletableFuture<>());
publisher.publish(event);
verify(kafkaTemplate).send("orders", "o-1", event);
}
@Test
void failedSendDoesNotThrow() {
OrderEvent event = new OrderEvent("o-2", 700);
when(kafkaTemplate.send("orders", "o-2", event))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("broker down")));
publisher.publish(event);
verify(kafkaTemplate).send("orders", "o-2", event);
}
}The first test pins the key choice. If someone changes the key, events for one order can land on different partitions and lose their ordering. The second test shows that a failed send is only logged, because the callback runs on the future and not on the caller's thread.
A unit test cannot tell you whether OrderEvent serializes. For that you need a broker.
Testing with an embedded broker
@EmbeddedKafka starts a Kafka broker inside the test JVM and publishes its address in the spring.embedded.kafka.brokers property. You point Spring Boot at it with a test property.
The class below runs two tests. One checks that the real listener receives a published event. The other reads the topic with an independent consumer, which checks the key and the JSON on the wire.
package com.example.orders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.kafka.test.context.EmbeddedKafka;
@SpringBootTest(properties = {
"spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}",
"spring.kafka.consumer.auto-offset-reset=earliest"
})
@EmbeddedKafka(partitions = 3, topics = "orders")
@ExtendWith(OutputCaptureExtension.class)
class OrderMessagingIT {
@Autowired
OrderPublisher publisher;
@Value("${spring.embedded.kafka.brokers}")
String brokers;
@Test
void listenerReceivesPublishedOrder(CapturedOutput output) {
publisher.publish(new OrderEvent("o-42", 1999));
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertThat(output.getOut()).contains("Received order o-42 for 1999 cents"));
}
@Test
void recordCarriesOrderIdKeyAndJsonValue() {
Map<String, Object> props = Map.of(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers,
ConsumerConfig.GROUP_ID_CONFIG, "verify-" + UUID.randomUUID(),
ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest",
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class,
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
consumer.subscribe(List.of("orders"));
publisher.publish(new OrderEvent("o-7", 250));
List<ConsumerRecord<String, String>> seen = new ArrayList<>();
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> {
consumer.poll(Duration.ofMillis(200)).forEach(seen::add);
assertThat(seen).anyMatch(r -> "o-7".equals(r.key())
&& r.value().contains("\"amountCents\":250"));
});
}
}
}Points to notice:
- Awaitility instead of sleep. Sending is asynchronous and the listener runs on another thread.
await().untilAsserted(...)retries until the assertion passes or the timeout expires, so the test is as fast as the system allows and fails with a clear message. - A separate consumer group. The verifying consumer uses a random group ID. It therefore does not take partitions from
order-serviceor move that group's offsets. - Reading strings. Deserializing to
Stringshows the actual JSON bytes. A wrong serializer configuration shows up here, and a test that deserializes back toOrderEventcan hide it. - Log capture.
OrderListeneronly logs, so the test asserts on its output. If your listener has side effects, such as saving to a database, assert on those instead.
The NewTopic bean from the setup chapter also runs during this test. @EmbeddedKafka creates orders first with three partitions, and the admin client sees that it exists.
Testing with Testcontainers
An embedded broker is convenient, but it is not the broker you run in production. Testcontainers starts a real Kafka image in Docker. With Spring Boot 3.1 or later, @ServiceConnection sets spring.kafka.bootstrap-servers for you.
package com.example.orders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
@SpringBootTest(properties = "spring.kafka.consumer.auto-offset-reset=earliest")
@Testcontainers
@ExtendWith(OutputCaptureExtension.class)
class OrderMessagingContainerIT {
@Container
@ServiceConnection
static KafkaContainer kafka =
new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:7.6.1"));
@Autowired
OrderPublisher publisher;
@Test
void listenerReceivesPublishedOrder(CapturedOutput output) {
publisher.publish(new OrderEvent("o-100", 4200));
await().atMost(Duration.ofSeconds(20)).untilAsserted(() ->
assertThat(output.getOut()).contains("Received order o-100 for 4200 cents"));
}
}This needs org.testcontainers:kafka and org.testcontainers:junit-jupiter as test dependencies, plus spring-boot-testcontainers. Container class names changed in newer Testcontainers releases, so check your version's documentation.
Common problems
- Test passes, then fails when run in a suite. All tests that share a Spring context also share the broker and its topics. Records from an earlier test stay in the topic. Use unique order IDs per test and assert on them, as the examples do.
- Listener never receives anything. The consumer may have started after the record was sent and used the default
latestreset. Setauto-offset-reset=earliestfor tests. NullPointerExceptionin the unit test. The mockedsendreturnednull. Stub it with aCompletableFuture.IllegalArgumentExceptionabout trusted packages. The JSON deserializer rejected the type. Your test properties may override thespring.json.trusted.packagessetting. Do not "fix" this with*in production configuration.- Embedded broker port conflicts. Do not hard-code a port. Always use
${spring.embedded.kafka.brokers}, which holds a random free port.
What to test beyond the happy path
The error-handling chapters configured retries and a dead-letter topic. Those need tests too, because misconfigured back-off or a missing .DLT topic fails only at runtime. A good approach is a test-only listener that always throws. The test then reads orders.DLT with a verifying consumer, as in the embedded-broker example, and expects the failed record after the retries are used up. Declare orders.DLT with a NewTopic bean in test configuration, so the recoverer has somewhere to publish.
Exercise
A listener test publishes an order and then asserts on the listener's result right away. It passes on your laptop and fails in CI. What is the likely cause, and how do you fix it?
Show answer
The listener runs asynchronously on a container thread, so the assertion can run before the record is consumed. On a fast machine it sometimes wins. Wrap the assertion in Awaitility's await().atMost(...).untilAsserted(...) so the test retries until the listener has run, and keep a bounded timeout so a real failure still fails the test.
Exercise
Why does the verifying consumer in the embedded-broker test use a random group ID, and what could go wrong if it used order-service?
Show answer
A consumer in the order-service group would join the same group as the application's listener. Kafka would split the partitions between them, so the listener might not receive the record and the test would behave unpredictably. It could also commit offsets for that group. A unique group ID gives the verifier its own copy of every record.