Android真机使用Mockito-1.10.19+Dexmaker-1.2在Mock继承抽象父类的子类时报告如下错误:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | java.lang.AbstractMethodError: abstract method not implemented at org.mockito.internal.invocation.AbstractAwareMethod.isAbstract(Native Method) at org.mockito.internal.invocation.InvocationImpl.callRealMethod(InvocationImpl.java:109) at org.mockito.internal.stubbing.answers.CallsRealMethods.answer(CallsRealMethods.java:41) at org.mockito.internal.stubbing.StubbedInvocationMatcher.answer(StubbedInvocationMatcher.java:34) at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:91) at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29) at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38) at com.google.dexmaker.mockito.InvocationHandlerAdapter.invoke(InvocationHandlerAdapter.java:49) at ChildCls_Proxy.forParentMock(ChildCls_Proxy.generated) at com.yunos.tv.shake.biz.DiTingMessageProviderTest.setUp(childClsTest.java:33) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:203) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:177) at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1727) | 
父类代码如下:
| 1 2 3 | abstract public class ParentCls {     abstract public void forChildMock(); } | 
子类代码如下:
| 1 2 3 4 5 6 7 | public class ChildCls extends ParentCls{     @Override     public void forChildMock() {     } } | 
测试代码如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class childClsTest extends AndroidTestCase {     @Override     protected void setUp() throws Exception {         super.setUp();         /*解决BUG dexcache == null (and no default could be found; consider setting the 'dexmaker.dexcache' system pr*/         System.setProperty(                 "dexmaker.dexcache",                 getContext().getCacheDir().getPath());         ChildCls childCls = Mockito.mock(ChildCls.class);         Mockito.doCallRealMethod().when(childCls).forParentMock();         childCls.forParentMock();     } } | 
在项目的build.gradle中的声明如下:
| 1 2 3 4 | //for mockito androidTestCompile 'org.mockito:mockito-core:1.10.19' androidTestCompile 'com.google.dexmaker:dexmaker:1.2' androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2' | 
这个问题只在Dalvik虚拟机下面发生异常,相同的代码在ART下面是完全正常的。
导致问题发生的原因是Google提供的dexmaker库存在BUG导致的,而这个库,从Maven Center上看,自从2012年开始就没有提供过任何的更新了。
解决方法是不使用Google提供的dexmaker,而是使用com.crittercism.dexmaker修正过这个BUG的版本。
| 1 2 3 4 5 | //for mockito androidTestCompile 'org.mockito:mockito-core:1.10.19' androidTestCompile 'com.crittercism.dexmaker:dexmaker:1.4' androidTestCompile "com.crittercism.dexmaker:dexmaker-dx:1.4" androidTestCompile 'com.crittercism.dexmaker:dexmaker-mockito:1.4' | 
com.crittercism.dexmaker项目的GitHub地址是https://github.com/crittercism/dexmaker






