Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a lambda callback with mockk

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?

like image 652
Janusz Avatar asked Dec 07 '18 16:12

Janusz


People also ask

What is callback () and how do I use it?

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.

What is a relaxed mock in Python?

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.

Why isn’t the mocked method intercepting the call?

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:

How do I get the parameter passed to a mock method?

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.


1 Answers

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.

like image 60
s1m0nw1 Avatar answered Sep 20 '22 12:09

s1m0nw1