Mock final classes on Kotlin

internal class Foo {
    internal fun bar(x: Int, y: Int, zip: Zip) = x + y + zip.doIt()
}
internal class Zip {
    internal fun doIt() = 0
}

When we have two classes like above and try to mock Zip class like below:

class FooTest {
    @Test
    fun testBar() {
        val foo = Foo()
        val zipMock: Zip = mock()
        whenever(zipMock.doIt()).doReturn(1)
        assertEquals(6, foo.bar(2, 3, zipMock))
    }
}

We will fail with the following exception:

org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class com.example.annotationopenfortesting.Zip
Mockito cannot mock/spy because : –
– final class

at com.example.annotationopenfortesting.FooTest.testBar(FooTest.kt:32)

Solution

Add to \src\test\resources\mockito-extensions
file with name org.mockito.plugins.MockMaker
and one line inside: mock-maker-inline

That’s it, so easy, now you can test the final classes.
Test passed!


One Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.