Hello everyone I am facing issues when writing uni...
# getting-started
p
Hello everyone I am facing issues when writing unit tests where the object under test internally calls an extension function. Assume I am writing a unit for my method A inside of which a 'mock' object calls a extension function and this class and its extension function are provided by 3rd party library. So when I write condition like
whenever(mockObj.callExtFunc()) return something
this would throw error something like:
java.lang.AbstractMethodError: Receiver class kotlin.jvm.functions.Function2$Subclass0 does not define or inherit an implementation of the resolved method 'abstract java.lang.Object invoke(java.lang.Object, java.lang.Object)' of interface kotlin.jvm.functions.Function2. at ....
Any thoughts. Thank you.
d
I recommend using mockk: https://mockk.io/#extension-functions
👍 2
p
ah, thanks, wasn't aware of this! This should help 👍
m
Other options are to see what the extension functions are doing and mock what they call or know that extensions functions are just static functions and mock the static functions. I found mockk too slow when I tried to use it even though I like the API better than mockito.
👍 1
p
My codes uses
HttpClient.post
from Ktor which is defined as an extension function in Ktor. So I have written conditions in my unit test as mentioned below:
Copy code
mockkStatic("io.ktor.client.request.BuildersKt")

coEvery {
    httpClientMock.post(any<String>(), any<HttpRequestBuilder.() -> Unit>())
} coAnswers { httpResponseMock }
But I still get this error when executing
coEvery
block. What could I be missing?
Meanwhile I used
ktor-client-mock
and handled differently but would appreciate if I can get an answer for my problem above.
m
I'm not sure what's wrong with the above. My guess would be that
BuildersKt
should be
buildersKt
since the file is lowercase in GitHub. But using
ktor-client-mock
would be my choice of solution. In general using a mocking library is my last choice when creating a test, because it typically creates the most fragile tests.
1
a
Was just about to write that you should use a client with
MockEngine
or the
services
block in your
TestApplicationEngine
instead of a mocking library for this, which should be the last resort in all circumstances.
p
@Michael Krussel I too thought it could be 'buildersKt' but then it throws 'ClassNotFoundException' !😬 @AdamW Can you please elaborate a bit for my better understanding?
p
got it, yeah, I am using MockEngine, thanks.