Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How does Mockito's static mock() method handle cleanup


How does Mockito's static mock() method handle cleanup


Mockito's `mock()` method, which is used to create mock objects, does not directly handle cleanup. However, Mockito provides several ways to ensure proper cleanup of mock objects:

1. Using `MockitoJUnitRunner` or `MockitoRule`:
- Mockito provides the `MockitoJUnitRunner` for JUnit 4 and `MockitoExtension` for JUnit 5, which automatically clean up mocks after each test method.
- The `MockitoRule` can also be used to automatically clean up mocks in JUnit 4 tests.
- These runners and rules handle the cleanup of mock objects created using `mock()` and other Mockito methods.

2. Manual cleanup with `reset()`:
- Mockito offers the `reset()` method to manually reset mocks to their default state.
- This can be useful in certain scenarios, but it's generally recommended to create new mocks rather than resetting existing ones, as it can lead to lengthy code and poor tests.

3. Cleanup with `verifyNoMoreInteractions()` and `verifyZeroInteractions()`:
- Mockito provides methods like `verifyNoMoreInteractions()` and `verifyZeroInteractions()` to verify that no other interactions happened on the mocks.
- These methods help ensure that mocks are not used in unexpected ways and can serve as a form of cleanup verification.

4. Using a `MockitoSession`:
- Mockito 3.4.0 introduced the `MockitoSession` class, which provides a more structured way to manage the lifecycle of mocks.
- With `MockitoSession`, you can start a session, create mocks, and then finish the session, which automatically verifies and cleans up the mocks.

While the `mock()` method itself does not handle cleanup, Mockito provides these additional mechanisms to ensure that mock objects are properly cleaned up after tests. The choice of cleanup approach depends on the specific needs of your test suite and personal preference.

Citations:
[1] https://ioflood.com/blog/mockito-verify/
[2] https://www.tutorialspoint.com/mockito/index.htm
[3] https://en.wikipedia.org/wiki/Mockito
[4] https://semaphoreci.com/community/tutorials/stubbing-and-mocking-with-mockito-2-and-junit
[5] https://www.digitalocean.com/community/tutorials/mockito-verify