Skip to content

Commit

Permalink
Added code to use public Mockito API introduced with
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreasTu committed Oct 5, 2023
1 parent 622bb65 commit 5f81e3a
Showing 1 changed file with 22 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.mockito.invocation.MockHandler;
import org.mockito.mock.MockCreationSettings;
import org.mockito.plugins.MockMaker;
import org.mockito.plugins.MockitoPlugins;
import org.spockframework.mock.CannotCreateMockException;
import org.spockframework.mock.IMockObject;
import org.spockframework.mock.ISpockMockObject;
Expand Down Expand Up @@ -57,18 +58,31 @@ class MockitoInlineMockMakerImpl {
spockMockMethod = ReflectionUtil.getMethodByName(ISpockMockObject.class, "$spock_get");
}

/**
* Resolves the inline mock maker of Mockito, via different ways, depending on the Mockito version.
*
* @return The inline mock maker of Mockito
*/
private MockMaker resolveInlineMockMaker() {
MockitoFramework framework = Mockito.framework();
MockitoPlugins plugins = framework.getPlugins();
try {
//First: Try to retrieve the internal inline mockMaker used by Mockito, to share the same static mocking state.
MockMaker mockMaker = (MockMaker) InvokerHelper.invokeStaticMethod(MockUtil.class, "getMockMaker", INLINE);
//First: Try to retrieve the inline mockMaker used by Mockito >= 5.6.0 public API, to share the same mocking state.
MockMaker mockMaker = (MockMaker) InvokerHelper.invokeMethod(plugins, "getMockMaker", INLINE);
return requireNonNull(mockMaker);

} catch (Throwable ex) {
//Fallback: Use our own InlineMockMaker instance from the Mockito public plugin API, but this will degrade the interoperability with Mockito static mocks.
//The own InlineMockMaker created here, does not share its state with the Mockito mock maker.
//It will work for all features, but if a class is mocked with both mock makers, it will yield strange behavior.
MockitoFramework framework = Mockito.framework();
return framework.getPlugins().getInlineMockMaker();
} catch (Exception ignored) {
try {
//Second: Try to retrieve the inline mockMaker used by Mockito < 5.6.0 with private method, to share the same mocking state.
MockMaker mockMaker = (MockMaker) InvokerHelper.invokeStaticMethod(MockUtil.class, "getMockMaker", INLINE);
return requireNonNull(mockMaker);

} catch (Exception ignored2) {
//Fallback: Use our own InlineMockMaker instance from the Mockito public plugin API, but this will degrade the interoperability with Mockito static mocks.
//The own InlineMockMaker created here, does not share its state with the Mockito mock maker.
//It will work for all features, but if a class is mocked with both mock makers, it will yield strange behavior.
return plugins.getInlineMockMaker();
}
}
}

Expand Down

0 comments on commit 5f81e3a

Please sign in to comment.