How to mock chain of calls someService.method1().method2()

for example I have a class

class MyClass {
@Autowired
SomeService someService;

@RequestMapping("/somepath")
public Object myMethod(){
  someService.method1().method2();
  //method2 is void
...
}

and MvcTest

@AutoConfigureMockMvc
class MyClassTest{
@MockBean
SomeService someService;

@Test
void test1(){
//how should be mocked this methods?
doNothing().when(someService.method1().method2()) //??
final MvcResult result = mockMvc.perform(get(String.format("/somepath")))
        .andExpect(status().isOk())
        .andReturn();
}
}
}

My question is: how correctly should be mocked this “chain” of methods?

  • you can use Mockito doAnswer and then continue your mocking.

    – 

I’m not saying that this is recommended nor that it’s a good idea, but in this simple case, you can instruct Mockito to have every method recursively return another mock object:

@MockBean(answer = Answers.RETURNS_DEEP_STUBS)
SomeService someService;

From the documentation:

WARNING: This feature should rarely be required for regular clean code! Leave it for legacy code. Mocking a mock to return a mock, to return a mock, (…), to return something meaningful hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).

Leave a Comment