Search code examples
cmocka

How can Cmocka test that my (void) callback function was called with the correct parameters?


I am using Cmocka for unit test and that cannot be changed.

I am testing part of my software which invokes callback functions, if a value changes, indicating which data item changed and what the new value is.

The callback functions have this signature:

typedef void (* Value_changed_call_back) (int item_Id, int new_value);

For unit test, I want to register some callback functions and ensure that they are actually invoked, and that they receive the correct parameters.

I can use expect_int() in my mocks, to validate that they are invoked with the correct parameters.

But, I don't see how I can use will_return() since my call back functions are of type void (and that can't be changed).

How would I declare a mock callback function and verify that it is called with the correct parameters? Note that if the function is not called, then the test should fail.


Solution

  • I think the best way to do what you want is to create a stub for the callback and register that. Then inside the callback you set some global variable to a value. Then you would be able to assert that value that gets set in your stub function. This works so long as the assert and the callback are executed on the same thread to make sure that the assert is not a race condition.