Robolectric + Mockito

2019-07-27 12:40发布

问题:

Trying to build android unit tests using Robolectric. Everytime I need to mock a method that belongs to my project it becomes slightly heavy to create a Shadow class. I think using Mockito in such cases would be much easier and lighter.

But when I try to use Mockito methods I get an error java.lang.IllegalArgumentException: dexcache == null (and no default could be found; consider setting the 'dexmaker.dexcache' system property)

In order to fix this I believe the dexcache property needs to be set by calling

System.setProperty("dexmaker.dexcache",getInstrumentation().getTargetContext().getCacheDir().getPath());

But I don't know getInstrumentation can be called while in Robolectric. Pls suggest a recommended approach to mock the methods of my Project in Robolectric.

回答1:

You can use Mockito with Robolectric; however, you need to make sure you're adding the "normal" Mockito dependency, and not the Mockito-Android or dexmaker dependency.

Mockito works by generating classes; on desktop JREs such as your unit test environment, that means generating Java CLASS files, but on Android devices and emulators that means generating DEX files. However, Mockito will opportunistically use DexMaker if it exists on the classpath, even when running outside of an emulator as Robolectric unit tests do. Adjust your dependencies to ensure that dexmaker is not included, which will avoid any problems with dexmaker or dexcache.



回答2:

A good way to separate your thinking about Robolectric and Mockito is

Mockito: Mock and verify your Java classes / non Android framework dependencies

Robolectric: Provides the TestRunner and working Android Framework elements where needed, e.g. Intent, Context

Build.gradle dependencies

dependencies {
    ...
    testCompile 'junit:junit:4.12'
    testCompile 'org.robolectric:robolectric:3.0'
    testCompile 'org.mockito:mockito-core:1.10.19'
}

Robolectric test runner

@RunWith(RobolectricTestRunner.class)
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}

Happy testing!