Reputation: 5736
In the following example
when(myMethod("abc", 123)).thenReturn(456);
How does the when()
method catch the method name and arguments without actually invoking myMethod()
?
Can I write a method to do the same thing as when()
so that I get a method pointer and an array of Object
s as arguments to invoke later?
Upvotes: 4
Views: 210
Reputation: 95614
In your above example, myMethod
is a method on a mock object. Without any expectations, Mockito will return null
, 0, or false depending on the data type, which when
will silently discard.
However, You may also use when
on an object which is not a mock, but rather an object created using Mockito.spy()
. In this case, the method would actually be called in the when
method, which is often not what you want to do. Mockito provides another method called doReturn
(or possibly doAnswer
or doThrow
) which provides you a replacement object so the original is never called (docs):
doReturn(1).when(mySpiedObject).getSomeInteger(anyString(), eq("seven"));
Note that the Mockito docs recommend using when
rather than doReturn
because the latter is not type-safe.
Upvotes: 0
Reputation: 88378
The method myMethod
is invoked. But it is being invoked on a mock object -- that's the "trick".
Of course you can write code that accepts a "method pointer" (in Java, it would be an object of class Method
) and some arguments, and use invoke
, but doing so does not actually buy you anything over calling the mock object's myMethod
directly.
It is more common to see when
called as follows:
MyObject myObject = mock(MyObject.class);
when(myObject.myMethod("abc", 123)).thenReturn(456);
Try printing (or logging) the expression
myObject.getClass().getName()
here. You will see that the class of the mock object is not actually MyObject
. But it is of a class that has the same interface. The calls on this object update some internal state. This allows Mockito to keep track of how it is used, and allows you to assert various things.
Upvotes: 2