Sub topic 14
Testing producers and listeners
This chapter assumes you have the OrderPublisher, OrderListener and OrderEvent classes from the earlier chapters. It also assumes you know JUnit 5 and @SpringBootTest. You will test the producer and the listener against a real broker instead of mocking KafkaTemplate.
Why mocks are not enough
A mocked KafkaTemplate proves only that your code called send. It does not check serialization, partition choice, the trusted-package setting or consumer group behavior. Most Kafka bugs live in those areas, so you need a real broker. There are two ways to get one.
| Option | Broker | Startup | Needs Docker |
|---|---|---|---|
| `@EmbeddedKafka` | In the test JVM | Fast | No |
| Testcontainers | Real Kafka container | Slower | Yes |
Use @EmbeddedKafka for most tests. Use Testcontainers when you need behavior that matches your production broker version. With @ServiceConnection, Spring Boot points spring.kafka.bootstrap-servers at the container for you.
Add the test dependency
Add spring-kafka-test to your build. Spring Boot manages its version.
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka-test</artifactId>
<scope>test</scope>
</dependency>The spring-boot-starter-test dependency already supplies JUnit, AssertJ and Awaitility.
Test the producer and the listener
@EmbeddedKafka starts a broker and writes its address into the property named by bootstrapServersProperty. Setting that property to spring.kafka.bootstrap-servers makes the application connect to the embedded broker instead of localhost:9092.
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.Map;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
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.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.support.serializer.JsonDeserializer;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.context.EmbeddedKafka;
import org.springframework.kafka.test.utils.KafkaTestUtils;
@SpringBootTest
@ExtendWith(OutputCaptureExtension.class)
@EmbeddedKafka(partitions = 3, topics = "orders",
bootstrapServersProperty = "spring.kafka.bootstrap-servers")
class OrderMessagingTest {
@Autowired
private OrderPublisher publisher;
@Autowired
private EmbeddedKafkaBroker broker;
@Test
void producerWritesKeyedJsonRecord() {
Map<String, Object> props = KafkaTestUtils.consumerProps("test-group", "true", broker);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
try (Consumer<String, OrderEvent> consumer = new DefaultKafkaConsumerFactory<>(
props, new StringDeserializer(), new JsonDeserializer<>(OrderEvent.class, false))
.createConsumer()) {
broker.consumeFromAnEmbeddedTopic(consumer, "orders");
publisher.publish(new OrderEvent("o-1", 2500));
ConsumerRecord<String, OrderEvent> record =
KafkaTestUtils.getSingleRecord(consumer, "orders");
assertThat(record.key()).isEqualTo("o-1");
assertThat(record.value()).isEqualTo(new OrderEvent("o-1", 2500));
}
}
@Test
void listenerReceivesOrder(CapturedOutput output) {
publisher.publish(new OrderEvent("o-2", 900));
await().atMost(Duration.ofSeconds(10))
.untilAsserted(() -> assertThat(output.getAll())
.contains("Received order o-2 for 900 cents"));
}
}The first test uses its own consumer group, test-group, so it does not steal records from the application's order-service group. The second test reads the listener's log output, because the listener has no other observable result.
Common errors
- Asserting too early. Listeners run on another thread. Use Awaitility with a timeout, and do not use
Thread.sleep. - Missing records. A new consumer group starts at the latest offset by default. Set
auto.offset.resettoearliestin your test consumer. - Wrong broker address. Without
bootstrapServersProperty, the application connects tolocalhost:9092and the test hangs. - Shared state between tests. A topic keeps its records for the life of the broker. Use unique order IDs, as above.
Exercise
A test publishes an order and then immediately asserts that the listener handled it. The assertion fails intermittently. Why, and what should you change?
Show answer
The listener runs asynchronously on a container thread, so the assertion can run before the record is consumed. Wait for the result with Awaitility's await().atMost(...).untilAsserted(...), or with Mockito's verify(mock, timeout(...)), instead of asserting right away.