Mocking replaces a collaborator’s real operation with a test double that implements the same interface and follows behavior configured by the test. This lets a unit test exercise one component without starting a Kafka broker or other external system. section 14.1
A mock-based test typically separates four responsibilities:
- Inject interface types into the class under test rather than concrete collaborators. section 14.1.1 section 12.1
- Configure the mock with the inputs and interactions required by the scenario; mocks provide no useful behavior automatically. section 14.1.1 section 14.1.2
- Run the component in isolation, then verify its output or interactions with the mock. section 14.1 section 14.1.2
- Reserve integration tests for cases requiring the real external component; those tests are broader and slower. section 14.1
Testing a currency exchange loop
A CurrencyExchangeClient receives transactions from a Consumer and sends converted transactions through a Producer. Construct it with Consumer and Producer interfaces, then supply MockConsumer and MockProducer instances. Queue a consumer task that establishes the input partition and offsets, a second task that adds euro, pound, and yen records, and a final task that calls close. Running the exchange loop now terminates deterministically; the test reads mockProducer.history() and compares the emitted transactions with the expected dollar conversions. section 14.1.1
Testing a Kafka Streams punctuator
Mockito can create a mock ProcessorContext and KeyValueStore for a StockPerformancePunctuator. Configure the store’s all() call to return an iterator containing a qualifying stock value, invoke punctuate(timestamp), and verify that the context forwards the expected record exactly once. section 14.1.2
Table 14.1 Unit testing compared to integration testing
|
Type
|
Purpose
|
Speed
|
Percentage of use
|
|---|---|---|---|
|
Unit
|
Method level, finer-grained logic, objects in isolation
|
Subsecond
|
Majority
|
|
Integration
|
Holistic, integrated components, course grained
|
Seconds to minutes
|
Minority
|
Compare unit and integration testing by purpose, execution speed, and typical share of the test suite. section 14.1




















