简体   繁体   English

如何在 Mockito 中模拟 instanceof

[英]How to Mock instanceof in Mockito

I have a piece of code, what I want test with Mockito:我有一段代码,我想用 Mockito 测试什么:

mockedClass instanceof SampleInterface

The mockedClass is mocked abstract class: MockedClass , and the SampleInterface is an Interface. mockedClass是被mockedClass的抽象类: MockedClass ,而SampleInterface是一个接口。 This is the failing point:这是失败点:

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

How to mock this code?如何模拟这段代码?

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.作为替代方案,创建一个用于测试的接口,扩展您希望模拟实现的所有接口,并以通常的方式模拟。

public abstract class ForTest implements SampleInterface {}

MockedClass mockedClass = mock(ForTest.class);

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM