When using a spied object as test subject, If we don't want to call nested methods inside the method we are testing, Which of these (doReturn-when or when-thenReturn) can be used to mock those nested methods? Is there a way to avoid getting invoked the real methods inside the method we are going to test?
In fact doesn't matter if you use doReturn-when or when-thenReturn method for this specific case, because considering a @Spy
you will always call the real method.
You can avoid entering other methods by mocking them, but if you are using just Mockito it will be a problem (it doesn't have this approach, but PowerMock does). Particularly I disagree with this approach, because we are being too intrusive in our tests and private flow is a part of the whole flow, but you can do something like this:
SomeService mock = spy(SomeService.class);
doReturn(1).when(mock, "getNumber", ArgumentMatchers.anyInt());
For more details, you can verify PowerMock's official documentation. Also, is nice to know some basic unit testing concepts (stubs, mocks and so on).