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
