lopez.mikhael
lopez.mikhael

Reputation: 10071

How to mock final class with Mockito 2 on Java Module in Android project?

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

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.

Upvotes: 4

Views: 8911

Answers (2)

makovkastar
makovkastar

Reputation: 5020

Mockito's MockMaker can only be used for unit tests (run on JVM). For those who are having problems with mocking Kotlin classes in instrumentation tests (androidTest), try using the DexOpener library. It makes Kotlin classes, properties and methods open, which allows their mocking.

Upvotes: 0

zsmb13
zsmb13

Reputation: 89578

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.

Upvotes: 19

Related Questions