测试Android应用程序与Robolectric和的Mocki

测试Android应用程序与Robolectric和的Mocki

本文介绍了安卓:单元测试Android应用程序与Robolectric和的Mockito的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用几件事情从Android API的Java库。我想使用的Mockito写单元测试这个库。

I have a Java library that uses a few things from the Android APIs. I'd like to use Mockito to write unit tests for this library.

有没有一种方法,我可以去吗?

Is there a way I can go about this?

的Mockito没有发挥好对Dalvik虚拟机,看到这个帖子:使用的Mockito与Android的虚拟机

Mockito doesn't play nice on the Dalvik VM, see this post: Using Mockito with Android virtual machine

更新:

由于这个职位,我已经发现Robolectric,我已经有机会制定出举足轻重的实验室,并到该库的一些小的贡献。我建议使用这种过度了Android测试框架/的Mockito。此外,你可以自由地使用Robolectric AND的Mockito,但在Robolectric影子对象进行的Mockito不必要的大多数用例。

Since this post I've discovered Robolectric, and I've had the opportunity to work out of Pivotal Labs and make some small contributions to this library. I would recommend using this over the Android testing framework/mockito. Also, you're free to use Robolectric AND Mockito, but the shadow objects in Robolectric make Mockito unnecessary for most use cases.

,试图单元测试Android上的问题是,你建立在Android库已每个方法灭掉要么抛出一个存根异常,或返回null。如果你想测试你的应用程序,并希望任何Android的行为,你的运气了,除非你使用Robolectric其重写在飞行时的类加载的字节级code,并注入模拟的行为阴影对象。

The problem with trying to unit test Android is that the Android library that you build on has every method stubbed out to either throw a stub exception, or return null. If you want to test your app and want any Android behavior you are out of luck, unless you use Robolectric which rewrites the byte-code on the fly when the classes load, and injects a shadow object that simulates the behavior.

更新2:

这已经有一段时间,事情发生了变化。许多在Robolectric暗影类都被替换为真正的Andr​​oid类。真正的Andr​​oid的罐子现在使用和Robolectric只会加载暗影类的一套东西要小得多。这更是一个理由使用Robolectric为你的Andr​​oid测试。

It's been a while and things have changed. Many of the Shadow classes in Robolectric have been replaced with the real Android classes. The real Android jars are now used and Robolectric only loads Shadow classes for a much smaller set of things. This is even more of a reason to use Robolectric for your Android testing.

推荐答案

在很多谷歌搜索,我所遇到的一个答案为此的。

After much Googling, I have come across an answer for this here.

基本上,它涉及到使用 Robolectric 的单元测试框架,它截获的安卓类的加载。然后,您可以继续使用的Mockito(虽然这是没有必要在大多数情况下),并运行测试在JVM上!

Basically it involves using the Robolectric unit testing framework, which intercepts the loading of the Android classes. You can then go ahead and use Mockito (although it isn't necessary in most cases) and run your tests on the JVM!

这篇关于安卓:单元测试Android应用程序与Robolectric和的Mockito的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:57