Robolectric + Mockito [英] Robolectric + Mockito

查看:55
本文介绍了Robolectric + Mockito的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 Robolectric 构建 android 单元测试.每次我需要模拟一个属于我的项目的方法时,创建一个 Shadow 类就会变得有点繁重.我认为在这种情况下使用 Mockito 会更容易、更轻松.

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.

但是当我尝试使用 Mockito 方法时,我得到一个错误 java.lang.IllegalArgumentException: dexcache == null(并且没有找到默认值;考虑设置 'dexmaker.dexcache' 系统属性)

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)

为了解决这个问题,我认为需要通过调用来设置 dexcache 属性

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

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

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

但我不知道在 Robolectric 中可以调用 getInstrumentation.请建议一种推荐的方法来模拟我在 Robolectric 中的项目的方法.

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.

推荐答案

您可以将 Mockito 与 Robolectric 一起使用;但是,您需要确保添加的是正常"的 Mockito 依赖项,而不是 Mockito-Android 或 dexmaker 依赖项.

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 通过生成类来工作;在桌面 JRE(例如您的单元测试环境)上,这意味着生成 Java CLASS 文件,但在 Android 设备和模拟器上,这意味着生成 DEX 文件.但是,如果类路径中存在 DexMaker,Mockito 会机会性地使用它,即使像 Robolectric 单元测试那样在模拟器之外运行也是如此.调整您的依赖项以确保不包含 dexmaker,这将避免 dexmaker 或 dexcache 出现任何问题.

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.

这篇关于Robolectric + Mockito的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆