MockitoAnnotationsopenMocksthis
MockitoAnnotations.openMocks is a method in the Mockito library used to initialize fields annotated with Mockito’s annotations in a test class, such as @Mock, @Spy, @Captor, and @InjectMocks. Unlike the earlier initMocks method, openMocks returns an AutoCloseable resource that manages the lifecycle of the initialized mocks, allowing explicit cleanup after tests.
Usage commonly involves obtaining a handle to the AutoCloseable returned by openMocks. In a JUnit 4 test,
OpenMocks serves as a modern alternative to MockitoAnnotations.initMocks(this). The latter initializes mocks but does not provide
In addition to openMocks, Mockito supports other initialization strategies. For JUnit 5, many users opt for