rob2universe
rob2universe

Reputation: 7628

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

My Java Azure Event Hub client implementation uses

<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventhubs</artifactId>
<version>5.0.3</version>

and

private static EventHubProducerClient producer;
 ...
EventDataBatch batch = producer.createBatch();
batch.tryAdd(new EventData(message.toString()));
producer.send(batch);

Mocking the producer works

@Mock
EventHubProducerClient producer;

but

@Mock
EventDataBatch dataBatch;
...
doReturn(dataBatch).when(producer).createBatch();

throws

org.mockito.exceptions.base.MockitoException: Cannot mock/spy class com.azure.messaging.eventhubs.EventDataBatch

There is no easy way to instantiate an EventDataBatch. The constructor requires a working connection.

Upvotes: 0

Views: 1993

Answers (1)

Lesiak
Lesiak

Reputation: 26074

You cannot mock com.azure.messaging.eventhubs.EventDataBatch as it is a final class. By default, Mockito does not allow to mock final classes.

This behaviour can be changed by using an extension. See Mock Final Classes and Methods with Mockito:

Before Mockito can be used for mocking final classes and methods, it needs to be configured.

We need to add a text file to the project's src/test/resources/mockito-extensions directory named org.mockito.plugins.MockMaker and add a single line of text:

mock-maker-inline

Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.

Upvotes: 2

Related Questions