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?
@InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock annotations into this instance. @Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class.
mock() method with Class: It is used to create mock objects of a concrete class or an interface. It takes a class or an interface name as a parameter. mock() method with Answer: It is used to create mock objects of a class or interface with a specific procedure.
A mock doesn't have any real implementation. @InjectMocks would try to find and call setters for whatever mock objects have already been created and pass them in.
Mockito @InjectMocks annotations allow us to inject mocked dependencies in the annotated class mocked object. This is useful when we have external dependencies in the class we want to mock. We can specify the mock objects to be injected using @Mock or @Spy annotations.
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 of someMethod()
) if we can just verify
that it's calling?
We can do it through:
@RunWith(MockitoJUnitRunner.class) class MyHandlerTest { @Spy @InjectMocks private MyHandler myHandler; @Mock private MyDependency myDependency; @Test public void testSomeMethod() { doReturn(1).when(myHandler).anotherMethod(); assertEquals(myHandler.someMethod() == 1); verify(myHandler, times(1)).anotherMethod(); } }
Note: in case of 'spying' object we need to use doReturn
instead of thenReturn
(little explanation is here)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With