简体   繁体   English

如何在robolectric测试中模拟/存根对象?

[英]How to mock/stub objects in robolectric tests?

What's the preferred way to mock/stub objects in robolectric tests? 在robolectric测试中模拟/存根对象的首选方法是什么?

My goal is to write Android code in TDD manner. 我的目标是以TDD方式编写Android代码。 Right now I am using interfaces and create mock classes that implement those interfaces in tests. 现在我正在使用接口并创建在测试中实现这些接口的模拟类。 This process is time consuming. 这个过程非常耗时。 Is there an easier way to stub a method of existing class in robolectric? 是否有更简单的方法来存在robolectric中现有类的方法?

I can only post my opinion about that topic. 我只能发表我对该主题的看法。

My preferred way is the MVP pattern. 我首选的方式是MVP模式。

  • java classes where you mock away views (android stuff) and test pure logic java类,你嘲笑视图(android东西)和测试纯逻辑
  • android classes where i mock my presenter and similar classes, the initialisation will be done by robolectric with just create phase. 在我的模拟我的演示者和类似类的android类,初始化将由robolectric完成,只需创建阶段。 most view methods are just delegator. 大多数查看方法只是委托人。

the second point works great because robolectric deliver already "stub" classes. 第二点很有效,因为robolectric已经提供了“存根”类。 all what i can't check with pure android will be checkable with shadow classes. 所有我无法用纯机器人检查的东西都可以用影子类来检查。

But maybe you just search for the Shadow classes functionality, http://robolectric.org/custom-shadows/ where you can stub methods. 但也许你只是搜索Shadow类功能, http: //robolectric.org/custom-shadows/你可以在哪里存根方法。

Update: here is also an example how I do it https://github.com/nenick/android-gradle-template/ 更新:这里也是我如何做的一个例子https://github.com/nenick/android-gradle-template/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM