我想模拟静态方法,因此使用依赖项“mockito-inline”3.8版本而不是“mockito-core”
静态方法模拟工作正常,但我的旧测试模拟接口失败并出现以下错误
org.mockito.exceptions.misusing.NotAMockException:
Argument passed to when() is not a mock!
Example of correct stubbing:
doThrow(new RuntimeException()).when(mock).someMethod();
恢复使用mockito-core可以解决问题,但是我将无法模拟静态方法
有什么方法可以为每个类选择不同的mockito引擎(子类/内联)?
如果您需要模拟静态方法并且无法使用
mockito-inline
,您可以使用 mockito-core
: 执行类似的操作
public class MockitoUtil {
public static <T, S> void mockStaticMethod(Class<T> classToMock, String nameOfMethodToMock, S result) {
MockCreationSettings<T> settings = mock(MockCreationSettings.class);
when(settings.isSerializable()).thenReturn(true);
MockHandler<T> handler = new MockHandler<>() {
private static final long serialVersionUID = 1L;
@Override
public Object handle(Invocation invocation) throws Throwable {
String invokedMethodName = invocation.getMethod().getName();
if(!invokedMethodName.equals(nameOfMethodToMock)){
String message = "called %s on class %s, but only %s was implemented";
throw new Exception(String.format(message, invokedMethodName, classToMock.getName(), nameOfMethodToMock));
}
return result;
}
@Override
public MockCreationSettings<T> getMockSettings() { return null; }
@Override
public InvocationContainer getInvocationContainer() { return null; }
};
MockMaker.StaticMockControl<T> classToMockControl = Mockito
.framework()
.getPlugins()
.getInlineMockMaker()
.createStaticMock(classToMock, settings, handler);
classToMockControl.enable();
}
}
NB. 如果您想在同一测试中模拟其他类的静态方法,则应该在静态方法调用之后调用
classToMockControl.disable()
MockResolver 修复了问题,如 https://github.com/mockito/mockito/issues/1980
中所述