#886
[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) );
[Raspberry] Code Java on the Raspberry Pi [Java] Redirect System.out & System.err to SLF4J
There is no way with Mockito to mock Private method.
Workarounds :
– Change private method to ‘default’, in this way, the Junit (if placed in the same package) can mocks the method
– Use PowerMock : https://dzone.com/articles/mock-private-method#mock-private-method
https://www.jayway.com/2012/02/25/mockito-and-dependency-injection/