如何在Mockito中模拟instanceof

如何在Mockito中模拟instanceof

本文介绍了如何在Mockito中模拟instanceof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,我想用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:

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:52