MockitoAnnotationsopenMocks
MockitoAnnotations.openMocks is a static helper in the Mockito framework used to initialize fields annotated with Mockito annotations in a test class. It processes annotations such as @Mock, @Spy, @Captor, and @InjectMocks on the provided test instance, creating the corresponding mock objects and injecting them where appropriate. Unlike the older initMocks method, openMocks returns an AutoCloseable resource that can be closed to release and reset mocks, enabling clean test setup and teardown.
Usage is typically straightforward. You obtain an AutoCloseable from openMocks and ensure it is closed after
AutoCloseable closeable = MockitoAnnotations.openMocks(this);
try {
// test code using @Mock, @Spy, etc.
} finally {
}
Or, in a try-with-resources block:
try (AutoCloseable closeable = MockitoAnnotations.openMocks(this)) {
}
OpenMocks is commonly used in place of the MockitoJUnitRunner or other test runners, particularly when using
Limitations and notes: openMocks initializes mocks for the specific test instance you pass and may need