在 Android 中效果最好的模拟库/框架? [英] Mocking library/framework that works best in Android?

查看:38
本文介绍了在 Android 中效果最好的模拟库/框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用第三方库 (Twitter4j) 开发 Android 应用程序.我希望能够在 JUnit 和功能测试中模拟这些对象(也是我创建的对象).

I'm developing Android application using third party libraries (Twitter4j). I want to be able mock those objects (also objects created by me) in JUnit and functional tests.

你在使用一些模拟库方面有什么好的经验可以推荐吗?

Do you have any good experiences using some mocking libraries and you can recommend them?

推荐答案

(更新:Mockito 从 1.9.5 版开始增加了对 Android 的支持,而 EasyMock 从 3.2 版开始通过分解出那些在运行时生成代码并使它们可插入,例如使用 dexmaker 而不是 cglib.)

除了 DixonD 提到的 android-mock(这是一个相当年轻的,未经证实的库),目前没有解决方案.您可以立即忘记基于 CGLib 的任何内容(Mockito,纯 EasyMock),因为 CGLib 依赖于字节码生成并且不能在 Dalvik 上工作(它还依赖于 Java Beans 包,它也不属于 Android).

Except for android-mock mentioned by DixonD (which is a fairly young, unproven library), there currently is no solution. You can immediately forget anything based on CGLib (Mockito, plain EasyMock), since CGLib relies on byte code generation and won't work on Dalvik (it also relies on the Java Beans package, which is also not part of Android).

就其价值而言,您可以使用 Android 附带的极少数模拟类(例如 MockContext),但它们不验证行为,它们只是存根.它们的默认行为是在每个方法中抛出运行时错误,因此您必须对它们进行子类化并覆盖您想要模拟的方法.

For what it's worth, you could use the very few mock classes coming with Android (like MockContext), but they don't verify behavior, they're just stubs. Their default behavior is to throw a runtime error in every method, so you have to subclass them and override the methods you want to mock.

但是,您仍然可以在非检测测试中使用模拟库,即在 JVM 上执行的标准单元测试中.您可以使用 PowerMock 来模拟框架方法,它支持模拟静态方法和构造函数,使得像eg一样强大的嘲讽在 Ruby 中(只是使用起来更痛苦).

However, you can still use mocking libraries in non-instrumentation tests, i.e. in your standard unit tests executed on the JVM. You can use PowerMock to mock framework methods, it has support for mocking static methods and constructors, making the mocking as powerful as e.g. in Ruby (just more painful to use).

我们使用 JUnit 4 + PowerMock + Mockito 并在我们继承每个普通 JUnit 测试的基类中模拟 Context 和 TextUtils 等类.对于仪器测试,我们创建自定义模拟类并决定使用工厂在运行时实例化哪个实现(模拟或不模拟).

We use JUnit 4 + PowerMock + Mockito and mock out classes like Context and TextUtils in a base class from which we inherit every normal JUnit test. For instrumentation tests, we create custom mock classes and decide using a factory which implementation (mock or not) to instantiate at runtime.

这篇关于在 Android 中效果最好的模拟库/框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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