2

I'll et the code speak.

@Test
fun test() {
    data class Activity(
        val type: String,
        val ts: Instant,
    )

    fun persistActivity(a: Activity): Unit = mockk()

    fun createActivity(type: String) {
        persistActivity(Activity(type, Instant.now()))
    }

    every { persistActivity(any()) } just Runs

    createActivity("foo")

    verify {
        persistActivity(Activity("foo", any()))
    }
}

However this fails with

Failed matching mocking signature for

left matchers: [any()]
io.mockk.MockKException: Failed matching mocking signature for

left matchers: [any()]

How can I verify persistActivity() was passed a data class with loose constraints on some of its fields? Can I achieve that without using cumbersome match {} function?

Jen
  • 1,206
  • 9
  • 30

1 Answers1

3

The persistActivity function is not mocked, so verification must fail. If it were mocked correctly though, you could use match for partial verification:

verify { persistActivity(match { it.type == "foo" }) }
Mafor
  • 9,668
  • 2
  • 21
  • 36
  • Thanks for your answer. As I wrote I simplified the code. In real life `persistActivity` would be OFC mocked. I edited the question to fix this. Can I achieve this without using the `match {}` function which is honestly quite cumbersome when the Activity data class has lots of fields? – Jen Jan 26 '21 at 10:41
  • Well, the closure passed to `match` could be anything. For example, you could try to reuse Kotest's `shouldBeEqualToIgnoringFields`. Alternatively you could try using mockk's capturing feature (https://mockk.io/#capturing) but it would be yet more cumbersome I guess. Yet another option: write your own extension function on the MockKMatcherScope. – Mafor Jan 26 '21 at 20:42
  • Right. Thanks for clarification. I was hoping that my attempt with putting the `any()` directly into the expected data class would just work as expected. World is not always that nice. .)) – Jen Jan 26 '21 at 22:12