by BehindJava
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.
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventhubs</artifactId>
<version>5.0.3</version>
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.
@Setter
EventHubProducerClient producer = new EventHubClientBuilder()
.connectionString(
"Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key}",
"event-hub-name")
.buildProducerClient();
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)) {
continue;
}
producer.send(batch);
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{
@Mock
Service service;
@Mock
EventHubProducerClient eventHubProducerClient;
@Mock
EventDataBatch eventDataBatch;
EventData eventData;
//Dummy Method to Mock the connection details and set the producer client
@BeforeEach
void preLoad()
{
service.setEventHubProducerClient(eventHubProducerClient);
}
@Test
void dummy_Tests()
{
when(eventDataBatch.tryAdd(any(EventData.class))).thenReturn(true);
Mockito.doReturn(eventDataBatch).when(eventHubProducerClient).createBatch();
doNothing().when(eventHubProducerClient).send(any(EventDataBatch.class))
}}
If you dont mock EventHubProducerClient right you may face this exception: com.azure.core.amqp.exception.AmqpException: Connection timed out: no further information, errorContext[NAMESPACE: myeventhub.servicebus.windows.net. ERROR CONTEXT: N/A]