Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito cannot mock/spy because : Final Class

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?

like image 700
LikseN Avatar asked Mar 03 '23 23:03

LikseN


2 Answers

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

like image 80
fangzhzh Avatar answered Mar 05 '23 16:03

fangzhzh


This approach for mocking final classes unfortunately doesn't work for UI tests. For your UI tests, you'll have to work with the kotlin allopen plugin.

like image 27
fweigl Avatar answered Mar 05 '23 16:03

fweigl