liveBook · Manning

MockProducer

As explained in Kafka Streams in Action, Second Edition

MockProducer is the Kafka client test class that implements Producer behavior without requiring a live Kafka broker.

MockProducer implements the Kafka Producer interface without requiring a live broker, allowing client applications to run producer logic in unit tests and expose the records they produced. section 14.1.1

Use MockProducer to:

  • Substitute for a Producer when the application depends on interfaces rather than concrete Kafka clients. section 14.1.1
  • Execute a currency-exchange client without starting Kafka, then verify converted output. section 14.1.1
  • Inspect sent records through history() and compare their values with expected transactions. section 14.1.1

Testing a currency exchange client

Construct CurrencyExchangeClient with a MockConsumer and MockProducer, schedule input records for euro, pound, and yen transactions, stop the exchange loop, and map mockProducer.history() to values for assertions against converted dollar transactions. section 14.1.1

Listing 14.2 Specifying interfaces in the constructor
public CurrencyExchangeClient(
   final Consumer<String, CurrencyExchangeTransaction>
 exchangeConsumer,                                       #1
   final Producer<String, CurrencyExchangeTransaction>
 exchangeProducer,                                    #2
   final String inputTopic,
   final String outputTopic) {

        this.exchangeConsumer = exchangeConsumer;
        this.exchangeProducer = exchangeProducer;
        this.inputTopic = inputTopic;
        this.outputTopic = outputTopic;
    }

Interface-based constructor injection makes MockProducer a direct replacement for the application's Producer dependency. section 14.1.1

How Kafka Streams in Action, Second Edition covers it

How deep it goes
Demonstrates interface substitution, recorded-output inspection, and assertions, but does not detail MockProducer internals.
Examples
Tests currency conversion by asserting euro, pound, and yen transactions recorded in producer history.
What it assumes
Assumes familiarity with Kafka Producer and Consumer interfaces while demonstrating interface-based dependency injection for testing.
What you can do after
Diagnose producer behavior by running client logic without Kafka and comparing recorded output with expected transactions.
How it connects
Connects Producer interfaces, MockConsumer, unit testing, integration testing, and Testcontainers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kafka Streams in Action, Second Edition. The section links point to the parts of the book it draws on.