java 如何在 Mockito 中模拟 instanceof

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27602598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:06:02  来源:igfitidea点击:

How to Mock instanceof in Mockito

javaunit-testingmockingmockito

提问by Gábor Csikós

I have a piece of code, what I want test with Mockito:

我有一段代码,我想用 Mockito 测试什么:

mockedClass instanceof SampleInterface

The mockedClassis mocked abstract class: MockedClass, and the SampleInterfaceis an Interface. This is the failing point:

是模拟mockedClass抽象类:MockedClassSampleInterface是接口。这是失败的地方:

Validate.isTrue(mockedClass instanceof SampleInterface, "The mockedClass is not a SampleInterface");

How to mock this code?

如何模拟这段代码?

回答by Jeff Bowman

It sounds like you need MockSettings.extraInterfaces.

听起来您需要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.

作为替代方案,创建一个用于测试的接口,扩展您希望模拟实现的所有接口,并以通常的方式模拟。

回答by tkruse

In addition to the other answer:

除了其他答案:

If possible, you should instead mock the interface, meaning create the mock like this:

如果可能,你应该模拟接口,这意味着像这样创建模拟:

SampleInterface mockedClass = mock(SampleInterface.class); // not mock(MockedClass)