2

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551

2 Answers2

2

I saw this post and thought about this in CMocka API. You can use expect_function_call(func) to indicates which function should be called and function_called() in the callback to mark the function as called.

I'm not sure since how long this feature is available (but present in 1.1.5 version).

I answered to this question in case someone comes across this topic even if it's a 2016 ask.

dchaudet
  • 51
  • 7
1

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.

Josh Kergan
  • 335
  • 3
  • 9
  • Sicne you are the only one who answered, I will award the quesition and the bonus points to you. If I don't, the system will auto-award you anyway, but you would only get half of the points. Welcome to Stack Overflow, and thanks for trying to help. – Mawg says reinstate Monica Jun 16 '16 at 12:17
  • 1
    @Mawg Thanks, I did take the time to look through the cmocha docs and that was the only solution I could think of. I've done similar setting of global variables when I care about order of execution in tests that I've done in the past. – Josh Kergan Jun 16 '16 at 13:47
  • The documentation isn't very good, is it? In fact, for something that was originally developed by Google, there is dearth of information available. However, teh way that the mock functions using GCC's linker `wrap` option is just so sweet that I can't find a better system. – Mawg says reinstate Monica Jun 17 '16 at 07:18
  • Well the only other way to do it would be with message passing, and it looks like cmocha doesn't want to deal with that. But it's stubbing and wrapping seem like really nice features. – Josh Kergan Jun 17 '16 at 18:22