Code Snippet

Just another Code Snippet site

[Test] Mockito : Mock & Spy

Mock

IServce mock = Mockito.mock(IService.class);

// Void method
when(mock.doSomething()).then(doSomething());

// With return
when(mock.doReturnSomething()).thenReturn("AA");

// Throw exception
when(mock.doSomething()).thenThrow(new IllegalArgumentException(""));

// With Argument
when(mock.doSomethingWithArgument(any(String.class))).thenReturn("BB");

// Return based on arguments
when(mock.doSomethingWithArgument(any(String.class)))thenAnswer(new Answer<String>() {
                    @Override
                    public String answer(InvocationOnMock invocation) throws Throwable {
                        Object[] args = invocation.getArguments();
                        return (String) args[0];
                    }
                });

Spy :

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.doReturn;

String a = "a";
String spy= Mockito.spy(a);

// The method toUpperCase is called once
when(spy.toUpperCase()).thenReturn(new String("B"));

// The method toUpperCase is neved called
doReturn(new String("B")).when(spy).toUpperCase();

To match any arguments :

import static org.mockito.Matchers.any;

...

//
doReturn(new String("A+B")).when(spy).concat( any(String.class) );


2 thoughts on “[Test] Mockito : Mock & Spy

Leave a Reply to Olivier Cancel reply

Your email address will not be published. Required fields are marked *