2

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!

MysteriousWaffle
  • 439
  • 1
  • 5
  • 16

1 Answers1

6

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)
        })
    }
}
Ice
  • 1,783
  • 4
  • 26
  • 52
  • I need `class X` to exist as well, but this has helped me indirectly get to an answer as `A` is a dataclass - thanks! – MysteriousWaffle Dec 08 '21 at 10:53
  • This is actually not answering the question. What if your constructor paramters are converted to some other data types when class in constructed? In this specific case you are just checking if the paramteres passed are matching the field params of the constructed class which has nothing to do with **"What I want to do is find out what A has been instantiated with."**. Surprisingly totally unrelated answer marked as correct – Farid Jun 16 '22 at 11:12