I have a Kotlin project using kotest as my unit testing framework and mockk to take care of my mocking requirements. I am new to all aspects of the Kotlin language and chosen testing libraries/frameworks.
I have a simple class in which a function creates an object which I want to spy on.
import java.net.URI
class MyClass {
public fun doStuff() {
val uri = URI("https://some-random-endpoint.com/get/some/stuff")
// ...
// ...use URI object to get some stuff
// ...
}
}
I would like to spy on the creation of the URI object to ensure it's passed the correct endpoint. Based off of the documentation I initially thought I could achieve my goal like this:
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.mockk.spyk
import java.net.URI
class MyClassTest : FunSpec({
test("doStuff should be targeting the correct endpoint") {
val urlSpy = spyk<URI>()
val myClass: MyClass = MyClass()
myClass.doStuff()
urlSpy.host shouldBe "some-random-endpoint.com"
urlSpy.path shouldBe "/get/some/stuff"
}
})
However, this fails as both urlSpy.host
and urlSpy.path
are null
.
I've clearly misunderstood something. I suspect the under-the-hood magic I was hoping for is not associating my spy with the creation of the URI object in MyClass.doStuff()
If I replace my spy with a mockk
then the creation of the URI object is mocked, as I would expect. However, a mock doesn't seem the correct object for me in this case... I don't want to mock the behaviour, I just want to verify the behaviour as it's coded.
Where am I going wrong?