https://kotlinlang.org logo
Title
m

maxmello

12/03/2018, 4:01 PM
Hello everybody, I want to test code that calls a repository, which I have mocked. I want the
repository.save(entity)
method to just return whatever is passed into it. I thought that
Slot
would be the correct way of doing this, but …
val slot = slot<Entity>()
every { repository.save(capture(slot)) } answers { slot.captured }
… does not work, because the slot.captured is lateinit and not initialized during initialization of the mocks. Am I missing something or is this not possible with mockK?
r

robin

12/03/2018, 7:18 PM
It's possible, but not with caputure slots. You can do smth like this:
every { repo.save(any()) } answers { invocation.args[n] as XYZ }
where XYZ is the type of the argument passed in.
I've actually built myself an extension function that does exactly that:
inline infix fun <reified T> MockKStubScope<T, T>.returnsArgument(n: Int): MockKAdditionalAnswerScope<T, T> =
    this answers { invocation.args[n] as T }
Called like:
every { repo.save(any()) } returnsArgument 0
o

oleksiyp

12/03/2018, 10:02 PM
Nice extension
I would expect slot stuff to be working actually
(please don't expect it to happen fast. I spend one weekend to fix stuff in mockk per 4-6 weeks)
m

maxmello

12/04/2018, 7:45 AM
Thank you both for the answers, very cool!