I create a mock of a class with mockk. On this mock I now call a method that gets a lambda as a parameter.
This lambda serves as a callback to deliver state changes of the callback to the caller of the method.
class ObjectToMock() { fun methodToCall(someValue: String?, observer: (State) -> Unit) { ... } }
How do I configure the mock to call the passed lambda?
You can use Callback () to log method calls and their parameters, which can help with troubleshooting. For example, let’s say you have a failing unit test and you can’t figure out why it’s failing. So you put in a Callback () to log the calls. This isn’t logging anything, which tells you the mocked method isn’t getting called at all.
A relaxed mock is the mock that returns some simple value for all functions. This allows you to skip specifying behavior for each case, while still stubbing things you need. For reference types, chained mocks are returned. Note: relaxed mocking is working badly with generic return types. A class cast exception is usually thrown in this case.
The mocked method is setup for Get (10), whereas you’re calling ProcessMessage (100), which is why the mocked method isn’t intercepting the call at all (and hence why it’s not invoking the Callback () lambda). This is just a typo. After fixing the problem, the test passes and outputs the following:
When you’re using Moq to set up a mocked method, you can use Callback () to capture the parameters passed into the mocked method: string capturedJson; mockRepo.Setup (t => t.Save (It.IsAny<string > ())) .Callback ( (string json) => { Console.WriteLine ("Repository.Save (json) called.
You can use answers
:
val otm: ObjectToMock = mockk() every { otm.methodToCall(any(), any())} answers { secondArg<(String) -> Unit>().invoke("anything") } otm.methodToCall("bla"){ println("invoked with $it") //invoked with anything }
Within the answers
scope you can access firstArg
, secondArg
etc and get it in the expected type by providing it as a generic argument. Note that I explicitly used invoke
here to make it more readable, it may also be omitted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With