英文:
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.
英文:
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.
答案1
得分: 1
您不能嘲笑com.azure.messaging.eventhubs.EventDataBatch
,因为它是一个最终类。默认情况下,Mockito不允许嘲笑最终类。这个行为可以通过使用扩展来改变。请参阅使用Mockito嘲笑最终类和方法:
> 在Mockito用于嘲笑最终类和方法之前,需要进行配置。
>
> 我们需要在项目的src/test/resources/mockito-extensions目录下添加一个名为org.mockito.plugins.MockMaker的文本文件,并添加一行文本:
> > mock-maker-inline >
> Mockito在加载时会检查扩展目录中的配置文件。这个文件启用了最终方法和类的嘲笑。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论