Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock instanceof in Mockito

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

mockedClass instanceof SampleInterface

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");

How to mock this code?

like image 262
Gábor Csikós Avatar asked Dec 22 '14 12:12

Gábor Csikós


2 Answers

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.

public abstract class ForTest implements SampleInterface {}

MockedClass mockedClass = mock(ForTest.class);
like image 105
Jeff Bowman Avatar answered Oct 21 '22 15:10

Jeff Bowman


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)
like image 42
tkruse Avatar answered Oct 21 '22 15:10

tkruse