89

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.

2 Answers 2

86

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.

Example:

import static org.mockito.Mockito.mockingDetails; 
assertThat(mockingDetails(probablyAMockedObject).isMock()).isTrue();
72

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).

7
  • 3
    Following on from your answer I took a look at the source for MockUtil and directly under the private isMockitoMock method there is a public isMock method that it seems can be used. I will post on the Mockito mailing list to check if it is a good idea to be calling methods from org.mockito.internal.util ourselves.
    – mikej
    Commented Jan 27, 2012 at 17:28
  • One of the intentions of the org.mockito.internal.util package is that the Mockito team could conceivably change anything in this package, in a newer version. So if you use this package, your tests could conceivably break in the future. However, it's extremely unlikely that we'd get rid of this particular method, so I'd say it's fairly safe to use. Commented Jan 27, 2012 at 18:32
  • @mikej: +1, somehow I missed that one, thanks! I removed the old answer and put your suggestion instead so it better stands out. Hope you don't mind. Commented Jan 27, 2012 at 18:33
  • 3
    OK, I've raised an issue on the Mockito issues register, to get isMock() added to the main Mockito class (that is, not internal). Unless someone else in the Mockito team objects, I will add this in the next release of Mockito. Commented Jan 27, 2012 at 18:44
  • 6
    @TomaszNurkiewicz, isMock has been added to the api. import org.mockito.Mockito.* mockingDetails(obj).isMock()
    – Raystorm
    Commented Jun 15, 2017 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.