How can I tell if an object is a Mockito mock?

JavaMockito

Java Problem Overview


Is it possible to tell in code if a given object is a Mockito mock or not?

The reason I'd like to do this is to return a different error message when a mock is being used. This would be used to suggest to other developers that they should use a pre-prepared mock that is already set to answer calls in a useful way rather than creating the mock themselves.

At the moment the best I have is object.getClass().getName().contains("EnhancerByMockitoWithCGLIB") but this feels hacky.

Java Solutions


Solution 1 - Java

Looks like there is no such API (please raise an issue, it should be!) Fortunately (following your comment below) there is a method in the org.mockito.internal.util package:

import org.mockito.internal.util.MockUtil;

new MockUtil().isMock(obj)

In the future Mockito.isMock() method might be added to public API, see: Issue 313: Provide isMock outside of org.mockito.internal).

Solution 2 - Java

As a follow up, the Mockito public API now has this method:

MockingDetails org.mockito.Mockito.mockingDetails(Object toInspect)

Which is the result of the issue that @David Wallace raised. The returned object supports the methods isMock() as well as isSpy() along with a few other methods that provide additional mocking information.

Solution 3 - Java

if you are using io.mockk.mockk then you can do :

isMockKMock()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmikejView Question on Stackoverflow
Solution 1 - JavaTomasz NurkiewiczView Answer on Stackoverflow
Solution 2 - JavaSpinaView Answer on Stackoverflow
Solution 3 - JavasurgaView Answer on Stackoverflow