rewrite-testing-frameworks
rewrite-testing-frameworks copied to clipboard
Mockito: Recipe to replace initMocks with openMocks
What problem are you trying to solve?
When upgrading Java applications and Mockito version, there is a MockitoAnnotiations API (initMocks) that is deprecated (see mockito-core 3.4.0 documentation for details).
What precondition(s) should be checked before applying this recipe?
The recommendation is to replace initMocks with openMocks(Object), which is equivalent to openMocks(testClass).close(). The close method should however only be called after completed usage of testClass. If using static-mocks or custom MockMakers, using this method might cause misbehavior of mocks injected into the test class.
Have you considered any alternatives or workarounds?
N/A
Any additional context
I'm not entirely sure if OpenRewrite has an existing utilities/mechanisms to simplify such complex refactorings, I wanted to surface this issue to check if there are any.
Are you interested in contributing this recipe to OpenRewrite?
N/A
Thanks for the suggestion @lucashan ! We should be able to convert such cases as described with a new recipe. We already have a similar recipe test to bring folks from JUnit 4 and Mockito 1 to JUnit 5 and Mockito v3; seems only logical to automate the next migration test involving initMocks / openMocks as well.
Ideally we start with a unit test similar to this one, describing exactly what we should aim for with this recipe. https://github.com/openrewrite/rewrite-testing-frameworks/blob/fafcb85d7c8c78ca3debfc563d91f55364067957/src/test/java/org/openrewrite/java/testing/mockito/JunitMockitoUpgradeIntegrationTest.java#L46-L122