How does if () work?

In the following example

when(myMethod("abc", 123)).thenReturn(456); 

How does the when() method catch the name and arguments of a method without actually calling myMethod() ?

Is it possible to write a method in order to do the same as when() in order to get a pointer method and an Object array as arguments to be called later?

+4
source share
2 answers

The myMethod method is myMethod . But it is called on the layout of the object - this is a "trick".

Of course, you can write code that accepts a "method pointer" (in Java, it will be an object of the Method class) and some arguments, and use invoke , but it will not actually buy you anything over calling the mock object myMethod directly.

Most common when :

 MyObject myObject = mock(MyObject.class); when(myObject.myMethod("abc", 123)).thenReturn(456); 

Try to print (or register) the expression

 myObject.getClass().getName() 

here. You will see that the mock object class is not really MyObject . But this is a class that has the same interface. Calls to this object update some internal state. This allows Mockito to keep track of how it is used, and allows you to state various things.

+2
source

In the above example, myMethod is a method on a mock object. Without any expectation, Mockito will return null , 0, or false depending on the type of data that when will silently drop.

However, you can also use when for an object that is not a layout, but rather an object created using Mockito.spy() . In this case, the method is actually called in the when method, which is often not what you want to do. Mockito provides another method called doReturn (or perhaps doAnswer or doThrow ) that provides you with a replacement object, so the original is never called ( docs ):

 doReturn(1).when(mySpiedObject).getSomeInteger(anyString(), eq("seven")); 

Note that Mockito docs recommend using when rather than doReturn , because the latter is not type safe .

0
source

Source: https://habr.com/ru/post/1438123/


All Articles