For example I have handler:
@Component
public class MyHandler {
@AutoWired
private MyDependency myDependency;
public int someMethod() {
...
return anotherMethod();
}
public int anotherMethod() {...}
}
to testing it I want to write something like this:
@RunWith(MockitoJUnitRunner.class}
class MyHandlerTest {
@InjectMocks
private MyHandler myHandler;
@Mock
private MyDependency myDependency;
@Test
public void testSomeMethod() {
when(myHandler.anotherMethod()).thenReturn(1);
assertEquals(myHandler.someMethod() == 1);
}
}
But it actually calls anotherMethod()
whenever I try to mock it. What should I do with myHandler
to mock its methods?
First of all the reason for mocking MyHandler methods can be the following: we already test
anotherMethod()
and it has complex logic, so why do we need to test it again (like a part ofsomeMethod()
) if we can justverify
that it's calling?We can do it through:
Note: in case of 'spying' object we need to use
doReturn
instead ofthenReturn
(little explanation is here)