MockProducerInterceptor.java

Overview

`MockProducerInterceptor.java` defines a mock implementation of the Kafka `ProducerInterceptor` interface designed primarily for testing purposes within the Apache Camel Kafka component. This interceptor captures Kafka `ProducerRecord` instances sent by the Kafka producer, storing them in a static list for later inspection or verification during unit or integration tests.

In Kafka, a `ProducerInterceptor` allows custom logic to be executed before a record is sent (`onSend`), after acknowledgment (`onAcknowledgement`), and during lifecycle events (`close`, `configure`). This mock implementation focuses on capturing the outgoing records without altering their content or behavior.


Class: MockProducerInterceptor

Description

Implements the `ProducerInterceptor` interface to intercept Kafka producer records. It collects all records sent via `onSend` into a public static list named `recordsCaptured`. Other lifecycle methods (`onAcknowledgement`, `close`, `configure`) are implemented as no-ops.

This class is useful in testing scenarios where capturing and asserting the records sent by a Kafka producer is necessary without affecting the producer's normal operation.

Package

`org.apache.camel.component.kafka`

Fields

Field Name

Type

Description

`recordsCaptured`

`ArrayList>`

Static list storing all captured `ProducerRecord` instances sent through the interceptor.

Methods

ProducerRecord<String, String> onSend(ProducerRecord<String, String> producerRecord)

void onAcknowledgement(RecordMetadata recordMetadata, Exception e)

void close()

void configure(Map<String, ?> configs)


Important Implementation Details


Interaction with Other System Components


Visual Diagram

classDiagram
    class MockProducerInterceptor {
        +static ArrayList~ProducerRecord<String, String>~ recordsCaptured
        +onSend(producerRecord: ProducerRecord<String, String>): ProducerRecord<String, String>
        +onAcknowledgement(recordMetadata: RecordMetadata, e: Exception): void
        +close(): void
        +configure(map: Map<String, ?>): void
    }

    MockProducerInterceptor ..|> ProducerInterceptor

Summary

`MockProducerInterceptor.java` provides a lightweight Kafka producer interceptor implementation that captures sent records for testing purposes. It enables developers to inspect Kafka messages produced by Apache Camel routes or other Kafka producers without interfering with normal message flow. Its simplicity and static storage facilitate easy access and verification of messages during automated testing. However, it is intended for testing and not for production use due to thread safety considerations and the lack of advanced interception logic.