简体   繁体   中英

Robolectric = Mockito : Cannot Create Mock or Spy In Mockito Because: dexcache == null

I have a well reported issue here:

Mockito + Dexmaker on Android

However the solution does not work.

I am using Robolectric and even when I try setting the dexmaker cache location:

@Before
public void setUp()
{
    System.setProperty("dexmaker.dexcache", RuntimeEnvironment.application.getCacheDir().getPath());
}

The error changes to

java.lang.RuntimeException: java.lang.NullPointerException

at com.android.dx.DexMaker.generateClassLoader(DexMaker.java:366)
at com.android.dx.DexMaker.generateAndLoad(DexMaker.java:439)
at com.android.dx.stock.ProxyBuilder.buildProxyClass(ProxyBuilder.java:264)
at com.android.dx.mockito.DexmakerMockMaker.createMock(DexmakerMockMaker.java:56)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
at org.mockito.Mockito.spy(Mockito.java:1368)

Do you have any ideas that will enable me to create Mock or Spy objects using Robolectric?

Note: When I don't use Robolectric and use a regular ActivityInstrumentationTestCase2 and @RunWith(AndroidJUnit4.class) I can create Mock and Spy objects...

This issue has arisen after Mockito 1.9

I just found this workaround:

https://comadeblog.wordpress.com/2013/11/12/dexcachenull-for-mockito-on-robolectric/comment-page-1/

TL;DR:

Use compile 'org.mockito:mockito-core:1.9.0' . Higher versions will throw this error.

This is the only way I have found to get it work with Robolectric.

Robolectric is used for unit tests that are run on build machine JVM. You don't need Dexmaker for these tests.

So please correct your build.gradle :

androidTestCompile "com.crittercism.dexmaker:dexmaker:${versions.dexmaker}"
androidTestCompile "com.crittercism.dexmaker:dexmaker-dx:${versions.dexmaker}"
androidTestCompile "com.crittercism.dexmaker:dexmaker-mockito:${versions.dexmaker}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM