我们在做单元测试或者其他测试的时候,可以使用Mockito实现Mock对象。
dependencies {
api 'org.mockito:mockito-android:3.0.0'
}
如果是非Android 运行环境请使用
dependencies {
api 'org.mockito:mockito-core:3.0.0'
}
可能会遇到 Could not initialize plugin: interface org.mockito.plugins.MockMaker
错误,该如何解决呢?
java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)
at org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:74)
at com.sun.proxy.$Proxy7.isTypeMockable(Unknown Source)
at org.mockito.internal.util.MockUtil.typeMockabilityOf(MockUtil.java:29)
at org.mockito.internal.util.MockCreationValidator.validateType(MockCreationValidator.java:22)
at org.mockito.internal.creation.MockSettingsImpl.validatedSettings(MockSettingsImpl.java:240)
at org.mockito.internal.creation.MockSettingsImpl.build(MockSettingsImpl.java:228)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:61)
at org.mockito.Mockito.mock(Mockito.java:1908)
at org.mockito.Mockito.mock(Mockito.java:1817)
或者
Caused by: java.lang.IllegalStateException: Error invoking java.lang.ClassLoader#defineClass
at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Direct.defineClass(ClassInjector.java:609)
at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.injectRaw(ClassInjector.java:236)
at net.bytebuddy.dynamic.loading.ClassInjector$AbstractBase.inject(ClassInjector.java:112)
at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default$InjectionDispatcher.load(ClassLoadingStrategy.java:232)
at net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:100)
at net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:5662)
解决方法
只需要使用 org.mockito:mockito-android
依赖,在调用mock之前,设置一下参数即可:
System.setProperty("org.mockito.android.target",getDir("target", Context.MODE_PRIVATE).absolutePath)
网友评论