How to mock methods with void return type?
I implemented an observer pattern but I can\'t mock it with Mockito because I don\'t know how.
And I tried to fin
How to mock void methods with mockito - there are two options:
doAnswer
- If we want our mocked void method to do something (mock the behavior despite being void).doThrow
- Then there is Mockito.doThrow()
if you want to throw an exception from the mocked void method.Following is an example of how to use it (not an ideal usecase but just wanted to illustrate the basic usage).
@Test
public void testUpdate() {
doAnswer(new Answer() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length > 1 && arguments[0] != null && arguments[1] != null) {
Customer customer = (Customer) arguments[0];
String email = (String) arguments[1];
customer.setEmail(email);
}
return null;
}
}).when(daoMock).updateEmail(any(Customer.class), any(String.class));
// calling the method under test
Customer customer = service.changeEmail("old@test.com", "new@test.com");
//some asserts
assertThat(customer, is(notNullValue()));
assertThat(customer.getEmail(), is(equalTo("new@test.com")));
}
@Test(expected = RuntimeException.class)
public void testUpdate_throwsException() {
doThrow(RuntimeException.class).when(daoMock).updateEmail(any(Customer.class), any(String.class));
// calling the method under test
Customer customer = service.changeEmail("old@test.com", "new@test.com");
}
}
You could find more details on how to mock and test void methods with Mockito in my post How to mock with Mockito (A comprehensive guide with examples)