The best way to mock a Java Azure EventHubProducerClient with Mockito is:

huangapple go评论89阅读模式
英文:

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

&lt;groupId&gt;com.azure&lt;/groupId&gt;
&lt;artifactId&gt;azure-messaging-eventhubs&lt;/artifactId&gt;
&lt;version&gt;5.0.3&lt;/version&gt;

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的文本文件,并添加一行文本:
> &gt; mock-maker-inline &gt;
> 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:
>
&gt; mock-maker-inline
&gt;

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

huangapple
  • 本文由 发表于 2020年8月12日 15:03:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63371486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定