methodsmockingmockitoequalsstub

Prevent stubbing of equals method


I would like to test my class' equals() method but Mockito seems to be calling the stub version every time. My test is as follows;

PluginResourceAdapter adapter = mock (PluginResourceAdapter.class);
PluginResourceAdapter other = mock (PluginResourceAdapter.class);

when(adapter.getNumberOfEndpointActivation()).thenReturn(1);
when(other.getNumberOfEndpointActivation()).thenReturn(0);

boolean result = adapter.equals(other);
assertFalse(result);

I know I cannot stub the equals method which means Mockito should be calling my real implementation but its not.

I have also tried this:

when (adapter.equals(any()).thenCallRealMethod()

but I get the same result.


Solution

  • Even beyond Mockito's limitations, it doesn't make much sense for a mocked object to use a real equals method, if for no other reason than that equals methods almost always use fields, and mocked objects never run any of their constructors or field initializers.

    Also, be aware of what you're testing: In a test of Foo, ideally you should never mock Foo, even to set up a Foo to compare against. Otherwise, it's easy to inadvertently test that Mockito works, rather than testing your own component's logic.

    You have a few workarounds:

    Note that one other potential workaround—spying on existing instances—will also redefine equals and hashCode and won't help you here.