doReturn
and thenReturn
in MockitoTwo ways to mock the result of a method:
doReturn
followed by when
when
followed by thenReturn
doReturn
followed by when
Notice that getByName
method is called after the when
method.
@Test
public void test() {
Cat cat = new Cat();
cat.setName('Tom');
CatServiceImpl catService = new CatServiceImpl();
// `doReturn` followed by `when`
// Note that `getByName` is called after`when`
doReturn(cat).when(catService).getByName(any());
Cat result = catService.getByName('Tom');
assertEquals('Tom', result.getName());
}
when
followed by thenReturn
Notice that getByName
method is called within the when
method.
@Test
public void test() {
Mouse mouse = new Mouse();
mouse.setName('Jerry');
MouseServiceImpl mouseService = new MouseServiceImpl();
// `when` followed by `thenReturn`
// Note that `getByName` is called within `when`
when(mouseService.getByName(any()).thenReturn(mouse);
Mouse result = mouseService.getByName('Jerry');
assertEquals('Jerry', result.getName());
}