如何在Android项目的Java Module上使用Mockito 2模拟最终课程? [英] How to mock final class with Mockito 2 on Java Module in Android project?

查看:75
本文介绍了如何在Android项目的Java Module上使用Mockito 2模拟最终课程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Android Clean Architecture项目用3个模块在Kotlin中编写:

I have a Android Clean Architecture project write in Kotlin with 3 modules:

  • 数据(Android库)
  • domaine(Java库)
  • 演示文稿(Android应用程序)

这3个模块均具有用junit编写的单元测试.但是对于Kotlin,默认情况下每个课程都是最终课程.我很快就遇到了一个问题:如何用模拟方法模拟最终课程

The 3 modules each have unit tests written with junit. But with Kotlin every class is final by default. I quickly had the problem: How to mock a final class with mockito

现在可以使用 Mockito 2

通过创建包含单行的文件/mockito-extensions/org.mockito.plugins.MockMaker,可以通过模仿扩展机制来完成:

It can be done via the mockito extension mechanism by creating the file /mockito-extensions/org.mockito.plugins.MockMaker containing a single line:

mock-maker-inline

此解决方案在数据模块(Android库)和 演示模块(Android应用程序),但不适用于我的 域模块(Java库).

This solution works very well on data module (Android Library) and presentation module (Android Application) but doesn't work on my domaine module (Java Library).

我知道已经问过这个问题(如何进行模拟带有嘲笑的最终类模拟调用final的对象使用Mockito对静态方法进行分类),但找不到所需的答案.

I know that this question has already been asked (How to mock a final class with mockito, Mock objects calling final classes static methods with Mockito), but I didn't find the answer I'm looking for.

推荐答案

默认情况下,可以通过从正常Mockito依赖项更改Gradle依赖项来使用内联模拟方法:

You can use the inline mocking method by default, by changing your Gradle dependency from the normal Mockito dependency:

compile "org.mockito:mockito-core:$mockito_version"

...到以下内容:

compile "org.mockito:mockito-inline:$mockito_version"

通过这种方式,您不必依靠通过资源文件夹中的文件"方法激活内联模拟,有时我发现这种方法很不稳定.

This way you won't have to rely on activating inline mocking with the "file in the resources folder" method, which I have found to be flaky sometimes.

这篇关于如何在Android项目的Java Module上使用Mockito 2模拟最终课程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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