Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

mockito

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.

like image 397
mikej Avatar asked Jan 27 '12 15:01

mikej


People also ask

How do you identify a mock object?

Mockito verify() method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method. We can use verifyNoMoreInteractions() after all the verify() method calls to make sure everything is verified.

Is Mockito mock object?

Mockito is a popular open source framework for mocking objects in software test. Using Mockito greatly simplifies the development of tests for classes with external dependencies. A mock object is a dummy implementation for an interface or a class. It allows to define the output of certain method calls.

How do I know if a method was called Mockito?

Verify in Mockito simply means that you want to check if a certain method of a mock object has been called by specific number of times. When doing verification that a method was called exactly once, then we use: ? verify(mockObject).

How can specify the mock Behaviour of an object?

When you create a mock, you create an associated behavior object that controls mock behavior. Use this object to define mock method and property behavior (stub). For more information on creating a mock, see Create Mock Object.


2 Answers

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

like image 156
Tomasz Nurkiewicz Avatar answered Sep 19 '22 13:09

Tomasz Nurkiewicz


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.

like image 29
Spina Avatar answered Sep 17 '22 13:09

Spina