Search code examples
androidunit-testingmockitorobolectricrobolectric-gradle-plugin

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


Solution

  • 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.