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?
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With