如何在Mockito中模拟instanceof [英] How to Mock instanceof in Mockito
问题描述
我有一段代码,我想用Mockito测试一下:
I have a piece of code, what I want test with Mockito:
mockedClass instanceof SampleInterface
mockedClass
是模拟的抽象类:MockedClass
,而SampleInterface
是一个Interface.这是失败的地方:
The mockedClass
is mocked abstract class: MockedClass
, and the SampleInterface
is an Interface. This is the failing point:
Validate.isTrue(mockedClass instanceof SampleInterface, "The mockedClass is not a SampleInterface");
如何模拟此代码?
推荐答案
It sounds like you need MockSettings.extraInterfaces
.
MockedClass mockedClass = mock(MockedClass.class,
withSettings().extraInterfaces(SampleInterface.class));
请注意,它带有自己的警告标签:
Note that it comes with its own warning label:
此神秘功能应经常使用.被测对象应确切知道其合作者和合作伙伴.依赖关系.如果您碰巧经常使用它,请确保您确实在生产简单,整洁的产品.可读的代码.
This mysterious feature should be used very occasionally. The object under test should know exactly its collaborators & dependencies. If you happen to use it often than [sic] please make sure you are really producing simple, clean & readable code.
作为替代方案,创建一个用于测试的接口,以扩展您要模拟实现的所有接口,并以通常的方式进行模拟.
As an alternative, create an interface for testing that extends all of the interfaces you want your mock to implement, and mock that the usual way.
这篇关于如何在Mockito中模拟instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!