使用 Mockito 模拟 Java Azure EventHubProducerClient 的最佳方法是什么?

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

我的Java Azure 事件中心客户端实现使用

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

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

嘲笑制作人作品

@Mock
EventHubProducerClient producer;

但是

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

投掷

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

没有简单的方法来实例化 EventDataBatch。构造函数需要有效连接。

你不能嘲笑 com.azure.messaging.eventhubs.EventDataBatch 因为它是最终的 class。默认情况下,Mockito 不允许模拟 final classes.

可以使用扩展程序更改此行为。见 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.