First question here!
I’m trying to do the following. I’ll avoid library details but basically I’m trying to mock an extension method provided by the Kotlin Aws sdk library, where a method is added to the io.File class that turns an opened File into a Bytestream. Thing is, there’s two overloaded methods for this. I’ve found ways to mock extension methods statically, and I can mock overloaded methods, but, I can’t find a way.
To replicate this I’m running this small block. While also defining a single extension method in another Kotlin file.
Extension.kt
fun File.extensionFunc(string: String): Int {
return string.toInt() + this.length().toInt()
}
Main.kt
val file = mockk<File>()
mockkStatic(File::extensionFunc)
every { any<File>().extensionFunc(any()) } returns 5
val result = file.extensionFunc("asdf")
assertEquals(5, result)
unmockkStatic(File::extensionFunc)
Which works fine! But if I add an extra extension method to File, same name, different arguments, I can’t figure out how to have this work without having the real extension method called (which obviously fails since the mocked file instance can’t return the length() function)
Extension.kt
fun File.extensionFunc(string: String): Int {
return string.toInt() + this.length().toInt()
}
fun File.extensionFunc(long: Long): Int {
return long.toInt() + this.length().toInt()
}
The main issue is that the mocckStatic
doesn’t compile to overload ambiguity.
Outside of this question’s original scope
This is a simplification of my problem. My situation runs a bit deeper because I do not own these extension methods myself but they are located in imported .class files (with kotlin syntax) from this AWS library.
Here’s a sample just in case, but this is outside of the question’s scope, and I’m hoping to find a solution of my own if I get the other problem fixed.
package aws.smithy.kotlin.runtime.content
public fun java.io.File.asByteStream(start: kotlin.Long = COMPILED_CODE, endInclusive: kotlin.Long = COMPILED_CODE): aws.smithy.kotlin.runtime.content.ByteStream { /* compiled code */ }
What’s different in my attempt here is that I’m trying to statically mock the whole class usingmockkStatic("aws.smithy.kotlin.runtime.content.ByteStreamJVMKt")
but that doesn’t do the trick either
Pedro Mattenet is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.