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 Objects as arguments to invoke later?
The method
myMethodis 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 useinvoke, but doing so does not actually buy you anything over calling the mock object’smyMethoddirectly.It is more common to see
whencalled as follows:Try printing (or logging) the expression
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.