Cristan
Cristan

Reputation: 14095

Capture vararg arguments with MockK?

You can mock a vararg method in MockK:

interface ClsWithManyMany {
    fun manyMany(vararg x: Any): Int
}

val obj = mockk<ClsWithManyMany>()
every { obj.manyMany(*anyVararg()) } returns 2
println(obj.manyMany("testing", "testing")) // 2

How can I capture the values passed to that method? This doesn't work (and neither does capturing a mutableListOf<Array<Any>>()):

val captured = slot<Array<Any>>()
every { obj.manyMany(*capture(captured)) } answers {
    println ("arguments: ${captured.captured}")
    2
}

Upvotes: 6

Views: 4152

Answers (1)

Cristan
Cristan

Reputation: 14095

You can do the following:

val captured = mutableListOf<Any?>()
every { obj.manyMany(*varargAllNullable { captured.add(it) }) } answers {
    println ("arguments: $captured")
    captured.clear()
    2
}

This issue is open to allow for a less hacky way to do this.

Upvotes: 13

Related Questions