Quickly solve Mocking with Kotlin

Akshay Chordiya
AndroidPub
Published in
1 min readOct 18, 2017

--

Recently I started tests for my complete project with Kotlin and I came across the “Mockito cannot mock/spy because : final class” problem because by default all classes in Kotlin are final.

This is not a new problem and a lot of people from the community have posted various blogs and answers regarding this problem (as shown below).

Existing solutions: MockMaker

Mockito solved the “cannot mock” problem in v2, by creating a file named org.mockito.plugins.MockMaker and placing this under the resources/mockito-extensions

Easy Peasy Solution

In this article, I just quickly want to introduce you to the easy way to solve the problem.

Just change your Mockito Gradle dependency from the Mockito core:

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

to the following:

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

TADA….it’s solved!

Easy Peasy!

Extra

Use Mockito-Kotlin library which provides some helper functions to make the Kotlin code much more concise and idiomatic.

Source: https://github.com/nhaarman/mockito-kotlin

Example

Before:

mock(FeedRepository::class.java)

With Mockito-Kotlin:

mock<FeedRepository>()

Final thoughts

I hope this article helped you quickly solve the mocking problem with Kotlin and help you focus on testing.

--

--

Akshay Chordiya
AndroidPub

Google Developer Expert @ Android | Android Engineer @ Clue | Instructor @Caster.IO