Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito call a method on a parameter of a mocked method

Tags:

java

mockito

I am just starting with Mockito and I just want to do something like :

public class Test {     
    public void clearList(List l){
        doVeryLOOOONGDatabaseCallll();
        l.clear();
        return;
    }
}

/// ... 
Test test = mock(Test.class);
Mockito.when(test.clearList(any(List.class))).then( l => l.clear());

Have some hint to do the trick? Thank you for your help!

like image 674
Thomas Avatar asked May 29 '13 16:05

Thomas


People also ask

Can you call method on mocked object?

Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it.

How do you call a mock method?

Mockito when() method It should be used when we want to mock to return specific values when particular methods are called. In simple terms, "When the XYZ() method is called, then return ABC." It is mostly used when there is some condition to execute. Following code snippet shows how to use when() method: when(mock.

How do you spy a method in Mockito?

Simple Spy Example Let's start with a simple example of how to use a spy. Simply put, the API is Mockito. spy() to spy on a real object. This will allow us to call all the normal methods of the object while still tracking every interaction, just as we would with a mock.


1 Answers

Something like this should do it (not tested):

doAnswer(new Answer() {
    public Object answer(InvocationOnMock invocation) {
        Object[] args = invocation.getArguments();
        List<?> list = (List<?>) args[0];
        list.clear();
        return null;
    }
}).when(test).clearList(any(List.class));
like image 176
JB Nizet Avatar answered Oct 22 '22 21:10

JB Nizet