Home > database >  How can I check the constructur arguments of a mockk Mock?
How can I check the constructur arguments of a mockk Mock?

Time:12-09

I have the following code (in Kotlin):

class X {
    fun foo() {
        val A(1, true, "three")
        val b = B()
        b.bar(A)
    }
}

What I want to to is find out what A has been instantiated with.

My test code looks like so:

// Needed for something else
every { anyConstructed<A>().go() } returns "testString"

// What I'm using to extract A
val barSlot = slot<A>()
verify { anyConstructed<B>().bar(capture(barSlot)) }
val a = barSlot.captured

How can I check what values A has been instantiated with now I've managed to capture the mock that was created when it was constructed (thanks to the every statement)?

Thanks!

CodePudding user response:

You can do it in two ways:

Using slot to capture the parameter:

@Test
fun shouldCheckValuesAtConstruct() {
    val a = A(1, true, "s")
    val b = mockk<B>()

    val aSlot = slot<A>()
    every { b.bar(a = capture(aSlot)) } returns Unit
    b.bar(a)
    val captured = aSlot.captured

    assertEquals(1, captured.a)
    assertEquals(true, captured.b)
    assertEquals("s", captured.s)
}

Or using withArg function and inline assertions

@Test
fun shouldCheckValuesAtConstructInlineAssertion() {
    val a = A(1, true, "s")
    val b = mockk<B>()

    every { b.bar(a) } returns Unit
    b.bar(a)

    verify {
        b.bar(withArg {
            assertEquals(1, it.a)
            assertEquals(true, it.b)
            assertEquals("s", it.s)
        })
    }
}
  • Related