Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run lambda function passed to a mockked method?

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.

like image 737
David Holkup Avatar asked Mar 24 '26 05:03

David Holkup


1 Answers

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.

like image 75
user2983377 Avatar answered Mar 25 '26 17:03

user2983377



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!