How to mock final classes in Kotlin with Mockito?


Let’s consider the following system under test:

class Repository {
  fun getAll(): List<String> {
    // retrieve or create list of strings somehow

// return only entries containing letter "g"
class UseCase(private val repository: Repository) {
  fun execute(): List<String> {
    return repository.getAll().filter { it.contains("g") }

And following test method:

class UseCaseTest {
  fun `it should return elements containing letter g`() {
    val mockRepository: Repository = mock {
      on { getAll() } doReturn listOf("kotlin", "testing", "blog")

    val useCase = UseCase(
      repository = mockRepository

    val result = useCase.execute()

    result.size shouldBe 2

if you are unsure how to use Mockito with Kotlin, check

After running this test it is likely that you will encounter the following error:

Cannot mock/spy class
Mockito cannot mock/spy because :
 - final class
  1. Classes marked as “final” should not be extended
  2. Kotlin default modifier translates to “final” in Java
  3. Classes in Kotlin are “final” unless specified otherwise (open class, abstract class)
  4. Mocking frameworks usually extend your class to do something with implementation details.

While the preferred solution is to use an interface for dependency, there is solution that will allow us to mock final classes with Mockito. To enable mocking final classes, configure MockMaker:

Configure MockMaker

In app/src/test/resources/mockito-extensions add file:


With contents:


org.mockito.plugins.MockMaker content

MockMaker location in project files

If you add this file in proper place and run tests again, class Repository will be properly mocked and error Mockito cannot mock/spy because your class is final class will be there no more.

Join AndroidPro newsletter & get roadmap for Android devs

👉 Architecture
👉 Testing
👉 Compose
👉 projects to learn from
… in a single document

Read more:

  • #kotlinDevChallenge – 10

    #kotlinDevChallenge – 10

    Implement a function that sums the first 5 even numbers from each of three given integer Flows and returns their total sum. Properly handle…

  • #kotlinDevChallenge – 9

    #kotlinDevChallenge – 9

    Write a function that takes a list of lists of integers and returns a single list containing all unique elements. Ensure that the resulting…

  • #kotlinDevChallenge – 8

    #kotlinDevChallenge – 8

    data class A is given. We create an instance of this class and then call the .copy() function. What will be printed out? Mark…