mockitoandroid_安卓:单元测试Android应用程序与Robolectric和的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 doesn't play nice on the Dalvik VM, see this post: Using Mockito with Android virtual machine

UPDATE:

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.

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.

UPDATE 2:

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.

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值