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.
To start using Mockito annotations we need to enable them first. There are three options to initialize them:
Mark JUnit test class with a @RunWith(MockitoJUnitRunner.class)
Using JUnit 4:
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.runner.RunWith;
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
}
Using JUnit 5:
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(MockitoExtension.class)
public class MockitoTest {
}
Call MockitoAnnotations.initMocks() in test class set up method usually annotated with @Before
public class MockitoTest {
@Before
public void setUp() {
MockitoAnnotations.initMocks()
}
}
Use dedicated @Rule public MockitoRule rule = MockitoJUnit.rule();
public class MockitoTest {
@Rule
public MockitoRule rule = MockitoJUnit.rule();
}
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}