Mockito Annotations
- @Mock
- @InjectMocks
- @Captor
- @Spy
1. @Mock Annotation
The @Mock annotation is used to create and inject mocked instances. We do not create real objects, rather ask Mockito to create a mock for the class.
The @Mock
annotation is an alternative to Mockito.mock(classToMock)
. They both achieve the same result. Using @Mock
is usually considered “cleaner and preferable“
Using the @Mock
annotation –
- allows shorthand creation of objects required for testing.
- Using @Mock we can minimizes repetitive mock creation code.
- Test class more readable with @Mock.
- makes the verification error easier to read because
field name
is used to identify the mock.
2. @InjectMocks Annotation
In Mockito, we need to create the object of class to be tested and then insert its dependencies (mocked) to completely test the behavior. To do this, we use @InjectMocks annotation.
@InjectMocks marks a field on which injection should be performed. Mockito will try to inject mocks only either by constructor injection, setter injection, or property injection – in this order. If any of the given injection strategies fail, then Mockito won’t report failure.
3. @Captor Annotation
The @Captor annotation is used to create an ArgumentCaptor
instance which is used to capture method argument values for further assertions.
Mockito verifies argument values using the equals()
method of argument class.
4. @Spy Annotation
The @Spy annotation is used to create a real object and spy on that real object. A spy helps to call all the normal methods of the object while still tracking every interaction, just as we would with a mock.
Initializing Mockito Annotations
To initialize the above annotation test class should initialize the annotation using one of the following given ways:
To initialize Mockito annotations with JUnit 5, we need to use below MockitoExtention :
@ExtendWith(MockitoExtension.class)
public class ApplicationTest {
//code
}
To Initialize JUnit 4, we can use either MockitoJUnitRunner or MockitoRule classes.
@RunWith(MockitoJUnitRunner.class)
public class ApplicationTest {
//code
}
public class ApplicationTest {
@Rule public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
//code
}