Research & Development projects
In this article, we implement the concept of callback in C++ and also use gmock as a way to test our code.
Callbacks exist in real life: you call someone, and they can not answer at that moment for any reason, you request a callback so that they call you at a later time. C++ has some Callables: functions, lambda expressions, bind expressions, function objects, and function pointers.
There is also a class template std::function which is a general-purpose function wrapper that can store, copy and invoke any Callable.
There are two types of callbacks, blocking ones (synchronous) and deferred ones (asynchronous).
The difference is blocking ones are called before the caller function returns so the caller actually waits for them to finish their job.
A simple example of std::fucntion below:
As an example of blocking/synchronous callback:
Now, let’s look into how std::function can be tested using gmock.
To mock std::function in tests, gmock provides MockFunction. First you need to create MockFunction object, obtain a std::fucntion proxy to Call from AsStdFucntion(), then set up expectations on its Call method and pass the obtained proxy to the test.
Below there is an example of the std::funciton and MockFunction in a unit test:
This simple example shows how MockFunction can be used in a handy way to mock std::function for testing purposes.