Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock String extension?

Tags:

kotlin

mockk

I'd like to mock a string extension.
I've read the instructions how this should be done, by using

mockStatic("kotlin.String")

or

mockkStatic("kotlin.kotlin_builtins")

but it keeps saying

Caused by: io.mockk.MockKException: Can't instantiate proxy for class kotlin.String
at io.mockk.impl.instantiation.JvmMockFactory.newProxy(JvmMockFactory.kt:64)
at io.mockk.impl.instantiation.AbstractMockFactory.newProxy$default(AbstractMockFactory.kt:29)
at io.mockk.impl.instantiation.AbstractMockFactory.spyk(AbstractMockFactory.kt:92)
at io.floriday.pdfgeneratorapi.integration.TradeItemListenerTest.<init>(TradeItemListenerTest.kt:131)
... 18 more
Caused by: io.mockk.proxy.MockKAgentException: Failed to create proxy for class java.lang.String.
class java.lang.String is one of excluded classes
at io.mockk.proxy.jvm.ProxyMaker.throwIfNotPossibleToProxy(ProxyMaker.kt:128)
at io.mockk.proxy.jvm.ProxyMaker.proxy(ProxyMaker.kt:28)
at io.mockk.impl.instantiation.JvmMockFactory.newProxy(JvmMockFactory.kt:34)
... 21 more

Probably I'm mocking the wrong file, but I can't seems to get the filename right to mock. Any help is appreciated :-D

like image 258
tomhier Avatar asked Nov 30 '25 21:11

tomhier


1 Answers

It is a question to your extension function. Where it resides? There is no general approach to all extension functions.

I found a lot of String related functions in kotlin.text.StringsKt. How I found it? I just went to the definition(source codes) of one String extension functions in IDEA and found @JvmName annotation to know exact class name.

Please try following thing:

mockkStatic("kotlin.text.StringsKt") {
    ...
}

If this doesn't help you basically need to find out what class you need. Just comment what extension function you need.

like image 74
oleksiyp Avatar answered Dec 03 '25 14:12

oleksiyp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!