1

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?

  • Maybe return URI from the method and check it instead? It's not clear what you are actually trying to test here – Evgeny Bovykin May 26 '21 at 16:42
  • Thanks @EvgenyBovykin. I did mention in my original post my intention for this very basic test: "I would like to spy on the creation of the URI object to ensure it's passed the correct endpoint" – user16039166 May 27 '21 at 08:33
  • There's a Constructor mock. IDK if that works for what you want https://mockk.io/#constructor-mocks . The `Spyk` bit won't spy on the constructor, it will only spy on the object itself, giving you an instance.` – LeoColman Jun 03 '21 at 19:45

0 Answers0