Kafka: Testing with an embedded broker

@EmbeddedKafka runs a real broker in the test JVM - no Docker, no mocks.

Code
@SpringBootTest
@EmbeddedKafka(partitions = 3, topics = { "orders" })
class OrderProducerTest {

    @Autowired KafkaTemplate<String, String> template;

    @Test
    void sendsToTheKeyedPartition() throws Exception {
        var md = template.send("orders", "order-42", "PLACED").get().getRecordMetadata();
        assertThat(md.partition()).isEqualTo(0);
    }
}
Output
The assertion holds because partitioning is deterministic:
murmur2("order-42") % 3 is the same on every machine and every run.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11