Introduction
Mockito is one of the most popular mocking frameworks for Java, empowering developers to isolate and thoroughly test their code with ease. By leveraging Mockito’s powerful features, you can create robust unit tests that simulate complex interactions, ensuring your code behaves as expected.
Understanding and utilizing Mockito annotations is key to writing clean, maintainable, and effective unit tests. This cheat sheet provides a quick reference to the most commonly used Mockito annotations, helping you streamline your testing process.
Mockito Annotations Cheat Sheet
Here’s a handy cheat sheet of the most commonly used Mockito annotations, ordered by their usage and popularity:
Mockito Annotation and Description
Mockito Annotation | Description |
---|---|
@Mock |
Creates a mock instance of a class or interface, allowing you to simulate behavior and interactions without needing an actual implementation. |
@Spy |
Creates a spy instance by wrapping around an existing object, enabling you to monitor and modify real method calls while still leveraging Mockito’s verification features. |
@InjectMocks |
Injects mock or spy instances into the tested object, ensuring dependencies are automatically mocked or spied upon without manual wiring. |
@Captor |
Creates an argument captor to capture method arguments passed to a mock during test execution. |
@MockBean |
Creates a mock bean in the Spring application context, ideal for integration tests that require mocked dependencies. |
@SpyBean |
Creates a spy bean in the Spring application context, allowing real method calls to be monitored and modified within a Spring environment. |
@RunWith(MockitoJUnitRunner.class) |
Runs tests with the Mockito JUnit runner, enabling Mockito annotations in JUnit 4 tests. |
@ExtendWith(MockitoExtension.class) |
Extends tests with the Mockito JUnit 5 extension, providing a modern and flexible testing setup. |
@BeforeEach |
Initializes mocks before each test method in JUnit 5. This annotation is part of the JUnit framework and ensures a fresh setup for each test. |
@AfterEach |
Cleans up mocks after each test method in JUnit 5. This annotation, also part of JUnit, ensures that each test starts with a clean state. |
Explanation of Key Annotations with Examples
@Mock Annotation
The @Mock
annotation creates a mock instance of a class or interface, allowing you to simulate behavior and interactions without needing an actual implementation.
Example:
@Mock
private List<String> mockList;
@Test
void testMock() {
mockList.add("test");
verify(mockList).add("test");
}
Explanation: The mockList
is a mock instance of List
. The verify
method checks that add("test")
was called on the mock list.
@Spy Annotation
The @Spy
annotation creates a spy instance by wrapping around an existing object, enabling you to monitor and modify real method calls while still leveraging Mockito’s verification features.
Example:
@Spy
private List<String> spyList = new ArrayList<>();
@Test
void testSpy() {
spyList.add("test");
verify(spyList).add("test");
assertEquals(1, spyList.size());
}
Explanation: The spyList
is a spy instance of ArrayList
. The verify
method checks that add("test")
was called, and the assertEquals
checks the size of the list.
@InjectMocks Annotation
The @InjectMocks
annotation injects mock or spy instances into the tested object, ensuring dependencies are automatically mocked or spied upon without manual wiring.
Example:
@Mock
private List<String> mockList;
@InjectMocks
private Service service;
@Test
void testInjectMocks() {
service.add("test");
verify(mockList).add("test");
}
Explanation: The mockList
is injected into the service
object. The verify
method checks that add("test")
was called on the mock list within the service.
@Captor Annotation
The @Captor
annotation creates an argument captor to capture method arguments passed to a mock during test execution.
Example:
@Mock
private List<String> mockList;
@Captor
private ArgumentCaptor<String> captor;
@Test
void testCaptor() {
mockList.add("test");
verify(mockList).add(captor.capture());
assertEquals("test", captor.getValue());
}
Explanation: The captor
captures the argument passed to add
. The assertEquals
method checks that the captured value is “test”.
@MockBean Annotation
The @MockBean
annotation creates a mock bean in the Spring application context, ideal for integration tests that require mocked dependencies.
Example:
@MockBean
private Service service;
@Autowired
private Controller controller;
@Test
void testMockBean() {
when(service.getData()).thenReturn("test");
assertEquals("test", controller.getData());
}
Explanation: The service
bean is mocked in the Spring context. The when
method specifies the behavior of the mock, and the assertEquals
checks the result from the controller.
@SpyBean Annotation
The @SpyBean
annotation creates a spy bean in the Spring application context, allowing real method calls to be monitored and modified within a Spring environment.
Example:
@SpyBean
private Service service;
@Autowired
private Controller controller;
@Test
void testSpyBean() {
doReturn("test").when(service).getData();
assertEquals("test", controller.getData());
}
Explanation: The service
bean is spied in the Spring context. The doReturn
method specifies the behavior of the spy, and the assertEquals
checks the result from the controller.
@RunWith(MockitoJUnitRunner.class) Annotation
The @RunWith(MockitoJUnitRunner.class)
annotation runs tests with the Mockito JUnit runner, enabling Mockito annotations in JUnit 4 tests.
Example:
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
@Mock
private List<String> mockList;
@Test
void testWithRunner() {
mockList.add("test");
verify(mockList).add("test");
}
}
Explanation: The MyTest
class runs with the Mockito JUnit runner, enabling Mockito annotations.
@ExtendWith(MockitoExtension.class) Annotation
The @ExtendWith(MockitoExtension.class)
annotation extends tests with the Mockito JUnit 5 extension, providing a modern and flexible testing setup.
Example:
@ExtendWith(MockitoExtension.class)
public class MyTest {
@Mock
private List<String> mockList;
@Test
void testWithExtension() {
mockList.add("test");
verify(mockList).add("test");
}
}
Explanation: The MyTest
class is extended with the Mockito JUnit 5 extension, enabling Mockito annotations.
@BeforeEach Annotation
The @BeforeEach
annotation initializes mocks before each test method in JUnit 5. This annotation is part of the JUnit framework and ensures a fresh setup for each test.
Example:
@ExtendWith(MockitoExtension.class)
public class MyTest {
@Mock
private List<String> mockList;
@BeforeEach
void init() {
mockList.clear();
}
@Test
void testBeforeEach() {
mockList.add("test");
verify(mockList).add("test");
}
}
Explanation: The init
method runs before each test method to initialize or reset the mock.
@AfterEach Annotation
The @AfterEach
annotation cleans up mocks after each test method in JUnit 5. This annotation, also part of JUnit, ensures that each test starts with a clean state.
Example:
@ExtendWith(MockitoExtension.class)
public class MyTest {
@Mock
private List<String> mockList;
@AfterEach
void tearDown() {
mockList.clear();
}
@Test
void testAfterEach() {
mockList.add("test");
verify(mockList).add("test");
}
}
Explanation: The tearDown
method runs after each test method to clean up the mock.
Download Mockito Cheat Sheet
Conclusion
Mockito annotations are essential for writing clean, effective, and maintainable unit tests. This cheat sheet provides a quick reference to the most commonly used Mockito annotations, helping you streamline your testing process and ensure your code’s reliability.
By mastering these annotations, you not only simplify the setup of your test environments but also enhance the overall quality and reliability of your codebase. These tools empower you to create more meaningful and precise unit tests, ensuring your application is robust and error-free. Keep this guide handy to enhance your productivity and take full advantage of Mockito’s capabilities. Happy testing!