by BehindJava

What is the best way to mock an Java Azure EventHubProducerClient with Mockito

Home » java » What is the best way to mock an Java Azure EventHubProducerClient with Mockito

In this blog, we are going to learn about mocking the EventHubProducerClient with Mockito in Java.

Firslty add this dependency into your pom.xml.


and refer to this official documentation of EventHubProducerClient

Create a producer and publish events to any partition as shown in the below Service class.

class Service{
    // The required parameter is a way to authenticate with Event Hubs using credentials.
// The connectionString provides a way to authenticate with Event Hub.
EventHubProducerClient producer = new EventHubClientBuilder()
List<EventData> events = Arrays.asList(new EventData("test-event-1"), new EventData("test-event-2"));

// Creating a batch without options set, will allow for automatic routing of events to any partition.
EventDataBatch batch = producer.createBatch();
for (EventData event : events) {
    if (batch.tryAdd(event)) {

    batch = producer.createBatch();
    if (!batch.tryAdd(event)) {
        throw new IllegalArgumentException("Event is too large for an empty batch.");

To Mock the above servie class firstly, use @Mock annotation to mock all the classes used in the service class as shown below.

class ServiceMock{
Service service;
EventHubProducerClient eventHubProducerClient;
EventDataBatch eventDataBatch;

EventData eventData;

//Dummy Method to Mock the connection details and set the producer client
void preLoad()

void dummy_Tests()

If you dont mock EventHubProducerClient right you may face this exception: Connection timed out: no further information, errorContext[NAMESPACE: ERROR CONTEXT: N/A]