Reputation: 442
I wonder whather it's possible to run a lambda function passed as a parameter to a mocked function. And run it whenever the mocked method is called.
I am using Mockk and I imagine the code to be something like this:
class DataManager {
fun submit(lambda: (Int) => Unit) { ... }
}
...
val mock = mockk<DataManager>()
every { mock.submit(lambda = any()) }.run { lambda(5) }
In my real implementation the datamanager calls a server and runs the lambda as a callback when it recieves a successful response. The lambda happens to be a private method of the class under test.
Upvotes: 11
Views: 6347
Reputation: 332
Can be solve in the following ways.
with args from answer:
every { dataManager.submit(any()) } answers {
firstArg<(Int) -> Unit>().invoke(5)
}
or with captureLambda
every { dataManager.submit(captureLambda()) } answers {
lambda<(Int) -> Unit>().captured.invoke(5)
}
Upvotes: 7
Reputation: 246
You need to use a Capture instead of Any.
val dataManager: DataManager = mockk()
every { dataManager.submit(captureLambda()) } answers { lambda<(Int) -> Unit>().invoke(5) }
dataManager.submit { i -> println(i) }
Additionally the the declaration of your function type is invalid.
You have (Int) => Unit
when it should be (Int) -> Unit
.
Upvotes: 17