Mockito is an open source Java framework for testing code. Mockito allows to mock objects and proxy method executions in automated unit tests. Mockito is helpful in creating mocks and spies in a simple and intuitive way, while at the same time providing great control of the whole process.
Mockito provides several annotations to reduce the line of code to make the code easy to read and maintain.
- @Mock - for creating mock objects, we can specify how a it should behave,
- @Spy - is for partial mocking, real methods are invoked, but we can still choose which one will be stubbed,
- @InjectMocks - inject objects annotated with @Spy or @Mock into test class,
- @Captor - mark special objects used to capturing the arguments passed into methods.
Useful Mockito articles
Mockito Cheat Sheet
Enable Mockito AnnotationsTo start using Mockito annotations we need to enable them first. There are three options to initialize them:
- Mark JUnit test class with a
Using JUnit 4: Using JUnit 5:
MockitoAnnotations.initMocks()in test class set up method usually annotated with
- Use dedicated
@Rule public MockitoRule rule = MockitoJUnit.rule();