Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock methods of @InjectMocks class?

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?

like image 714
Vova Yatsyk Avatar asked Jun 11 '15 07:06

Vova Yatsyk


People also ask

What is the difference between @InjectMocks and @mock?

@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.

How do you do mock method?

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.

Can we use mock and InjectMocks together?

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.

How do you mock an injected object?

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.


1 Answers

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)

like image 72
Vova Yatsyk Avatar answered Sep 29 '22 19:09

Vova Yatsyk