Hello everybody, I want to test code that calls a ...
# mockk
m
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 …
Copy code
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
It's possible, but not with caputure slots. You can do smth like this:
Copy code
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:
Copy code
inline infix fun <reified T> MockKStubScope<T, T>.returnsArgument(n: Int): MockKAdditionalAnswerScope<T, T> =
    this answers { invocation.args[n] as T }
Called like:
Copy code
every { repo.save(any()) } returnsArgument 0
o
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
Thank you both for the answers, very cool!