Getting Started with Mockito @Mock and @InjectMocks
In this article we see the meaning of @Mock
and @InjectMock
annotations.
Below the class we are going to Mock.
public class MockedService { public String doMockedStuff() { return "hello"; } }
@Mock
annotation
Here the class we are going to test.
public class ServiceToTest { private MockedService mockedService; public ServiceToTest(MockedService mockedService) { this.mockedService = mockedService; } public String doStuff() { return mockedService.doMockedStuff(); } }
Now the test case.
import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class UnitTestApplicationTests { @Mock private MockedService mockedService; @Test public void testMock() { when(mockedService.doMockedStuff()).thenReturn("mock hello"); ServiceToTest serviceToTest = new ServiceToTest(mockedService); assertEquals("mock hello", serviceToTest.doStuff()); } }
As you can see mocked instance mockedService
is passed as constructor argument to declared instance of ServiceToTest
.
@InjectMock
annotation
Below the modified class of ServiceToTest
when instance of MockedService
in not passed as constructor argument. An example of this scenario is when you test class with attributes annotate with Spring @Autowired
annotation.
public class ServiceToTest { private MockedService mockedService; public ServiceToTest() { } public String doStuff() { return mockedService.doMockedStuff(); } }
Here the test class when we declare a instance of ServiceToTest
annotated with @InjectMocks
. In this way Mock of mockedService
is automatically injected into serviceWithInject
.
import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class UnitTestApplicationTests { @Mock private MockedService mockedService; @InjectMocks private ServiceToTest serviceWithInject = new ServiceToTest(); @Test public void testInjectMock() { when(mockedService.doMockedStuff()).thenReturn("inject mock hello"); assertEquals("inject mock hello", serviceWithInject.doStuff()); } }