问题描述
我有一个 Android Clean Architecture 项目用 Kotlin 编写,包含 3 个模块:
- 数据(Android 库)
- domaine(Java 库)
- 演示文稿(Android 应用程序)
这 3 个模块每个都有用 junit 编写的单元测试.但是对于 Kotlin,默认情况下每个类都是 final 的.我很快就遇到了问题:如何使用 mockito 模拟 final 类
现在可以使用 Mockito 2
可以通过 mockito 扩展机制通过创建包含一行的文件 /mockito-extensions/org.mockito.plugins.MockMaker
来完成:
mock-maker-inline
<块引用>
此解决方案在数据模块(Android 库)和演示模块(Android 应用程序)但不适用于我的域模块(Java 库).
我知道这个问题已经被问过了(如何模拟带有 mockito 的 final 类,模拟对象调用 final使用 Mockito 类静态方法),但我没有找到我正在寻找的答案.
您可以默认使用内联模拟方法,通过将您的 Gradle 依赖项从普通的 Mockito 依赖项更改:
编译org.mockito:mockito-core:$mockito_version"
...到以下内容:
编译org.mockito:mockito-inline:$mockito_version"
这样您就不必依赖使用资源文件夹中的文件"方法来激活内联模拟,我发现这种方法有时很不稳定.
I have a Android Clean Architecture project write in Kotlin with 3 modules:
- data (Android Library)
- domaine (Java Library)
- presentation (Android Application)
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
It's now possible with Mockito 2
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
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).
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.
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"
... to the following:
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 模块上使用 Mockito 2 模拟最终类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!