Mockito + Dexmaker on Android

前端 未结 7 562
余生分开走
余生分开走 2020-12-05 09:42

I am trying to use Mockito in my Android project. I have found very nice tutorial that deals with it: http://www.paulbutcher.com/2012/05/mockito-on-android-step-by-step/

7条回答
  •  一向
    一向 (楼主)
    2020-12-05 10:10

    So the problem is with Dexmaker not being able to find the cache path on Android >= 4.3 as other people mentioned and as described in this dexmaker issue.

    I went with implementing the workaround in a custom instrumented test runner instead of in every test (or their superclass) setUp(), because it feels a bit less hacky (it really is in only one place - and not inherited in every subclass) and more flexible. For the sake of documentation these are the necessary changes to do this:

    public class CustomInstrumentationTestRunner extends InstrumentationTestRunner {
    
        @Override public void onCreate (final Bundle arguments) {
            super.onCreate(arguments);
    
            // temporary workaround for an incompatibility in current dexmaker (1.1) implementation and Android >= 4.3
            // cf. https://code.google.com/p/dexmaker/issues/detail?id=2 for details
            System.setProperty("dexmaker.dexcache", getTargetContext().getCacheDir().toString());
        }
    }
    

    And set up your project (or test project) to use this class as the instrumented test runner in its AndroidManifest.xml when building with ant:

    
    

    or its build.gradle when building with gradle:

    android {
        defaultConfig {
            // ...
            testInstrumentationRunner 'my.package.CustomInstrumentationTestRunner'
        }
        // ...
    }
    

    If you have other instrumentation entries, you can switch between them either on the command line or select one in your IDE running configuration.

提交回复
热议问题