Mocking an object should not call init {}
mockk() seems to be calling class init{}
coEvery {
httpClient.get<HttpStatement>(any<HttpRequestBuilder>())
} returns mockk()
//...
class HttpStatement(
private val builder: HttpRequestBuilder,
private val client: HttpClient
) {
init {
checkCapabilities() // this method keeps getting called when i try to create the mock
}
//...
}
Error being caused due to init {} being called
java.lang.NullPointerException
at io.ktor.client.statement.HttpStatement.checkCapabilities(HttpStatement.kt:130)
at io.ktor.client.statement.HttpStatement.
+1.
I have some generated code that loads a library inside its companion init{} block, which isn't available on the test classpath. Instead of mocking System.loadLibrary via mockkStatic (which has bad side effects), i'd like to find a way to mock an object without its init{} block being called.
class User constructor (private val self: Long) {
companion object {
init {
try {
System.loadLibrary("android")
} catch (e: UnsatisfiedLinkError) {
System.err.println("Native code library failed to load.")
System.err.println("$e")
exitProcess(1)
}
}
...
}
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. If you are sure that this issue is important and should not be marked as stale just ask to put an important label.
I have the same use case. Is there any known workaround?
I found similar questions here: https://github.com/mockk/mockk/issues/261
Not sure if I should open a new issue for this?
In my case I gave up from the issue and avoided the mock by using ktor MockEngine, but the problem still there, no way of mocking objects with init logics
I worked around the issue by mocking the System call in a mockkStatic block, then calling mockkClass(it) which calls init {} which calls the static system mock. Works well enough for me.
```
fun initRustBindings(vararg rustBindings: KClass<*>) {
mockkStatic("java.lang.System") {
every { System.loadLibrary("android") } returns Unit
rustBindings.forEach {
mockkClass(it)
println("Mocked ${it.simpleName}")
}
}
}
First thanks for the replies.
My specific problem is that the init block calls a jni method. Can those be mocked to?
Most helpful comment
I have the same use case. Is there any known workaround?
I found similar questions here: https://github.com/mockk/mockk/issues/261
Not sure if I should open a new issue for this?