VerifyError using Mockito 1.9.5 and DexMaker-Mockito-1.0

雨燕双飞 提交于 2019-11-30 17:12:22
Shilaghae

Hi I had the same problem and I found this article really usefull!

http://corner.squareup.com/2012/10/mockito-android.html

The key piece of information is:

To use Mockito on a device or emulator, you’ll need to add three .jar files to your test project’s libs directory: mockito-all-1.9.5.jar, dexmaker-1.0.jar, and dexmaker-mockito-1.0.jar.

Just add this in your gradle:

androidTestCompile 'org.mockito:mockito-core:1.10.8'
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.1'

We just had the same problem in a project, but our tests also failed on a real device.

The cause was tracked to how Mockito uses the class loader, and resulted in the following error in LogCat:

W/ActivityThread(5777): ClassLoader.getResources: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());

The fix was to explicitly set the class loader before calling mock() a test, eg.

@Override
protected void setUp() throws Exception {
    super.setUp();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    fooImpl = mock(Foo.class)
}

The problematic file in Mockito is this one: org.mockito.internal.configuration.ClassPathLoader (line 121 in 1.9.5)

As hinted at here the dexmaker-android combo only works 100% when the instrumented tests are run against a real device.

Running the tests against a real device do not exhibit this failure.

For everybody who still have this error, check if you didn't exclude a class in the dependecies. We exluded by accident the MockMaker.class so this was then the cause for the exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!