How to get Mockito to do something every time a method is called on the layout?

I am trying to achieve this behavior with Mockito:

When an object of type O is applied to method M, the layout must execute another method for an object of type O that passes itself as a parameter.

Is it possible?

+4
source share
1 answer

You can probably use a combination of doAnswer and when in combination with Mockito.any . doAnswer is part of PowerMockito , which helps extend many of the bullying you might want to do.

NOTE. doAnswer used as an example for void functions. For non-void, you can use your standard Mockito.when(MOCK.call).then(RESULT)

 PowerMockito.doAnswer(new org.mockito.stubbing.Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { //Do whatever to Object O here. return null; }).when(MOCKOBJECT.methodCall(Mockito.any(O.class))); 

In this case, the doAnswer functionality is doAnswer for a mock object, and with when you can assign it to search for any specific object class (instead of specifying the exact object it should expect). Using Mockito.any(Class.class)) as part of the parameters lets Mockito know to turn off your action no matter when it accesses a method call with ANY object of the specified type passed to.

+5
source

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


All Articles