Mockito cannot mock/spy because : Final Class

LikseN picture LikseN · Jan 3, 2020 · Viewed 11.3k times · Source

I know this question is asked a lot of time, but I followed a lot of answer and it still didnt work

How to mock a final class with mockito

in this link, they said that we have to add in our gradle :

testImplementation 'org.mockito:mockito-inline:2.13.0'

=> Currently I have

testImplementation "org.mockito:mockito-inline:2.28.2"

I also have this single line in my MockMaker file :

mock-maker-inline

Then you can see my following code :

object ApiHelper {

fun <T> createService(
        url: String,
        clazz: Class<T>
    ): T
}

in my UITEST

    @Mock
    private lateinit var service: myService

    private lateinit var apiHelper: ApiHelper

    @Before
    fun setUp() {

        apiHelper = mock(ApiHelper::class.java)

        given(ApiHelper.createService(
            anyString(),
            MyService::class.java,
        )).willReturn(service)
    }

What is wrong with my code? Did I missed something?

Answer

fangzhzh picture fangzhzh · Jan 3, 2020

mocking library for Kotlin http://mockk.io

I also used mockito before, it has so many problems when writing.

Instead, the mockk is powerful and it makes your testing easier to write and

object mocks is just for your case