且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Android 项目的 Java 模块上使用 Mockito 2 模拟最终类?

更新时间:2022-10-23 12:52:12

您可以默认使用内联模拟方法,通过将您的 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.