C++ developers Archives - Sigma IT
Skip to content
MENU
LANGUAGE
TECHNICAL INSIGHTS
SOFTWARE DEVELOPMENT

A practical guide to implementing and testing callbacks in C++ and gmock

article_implementing_callbacks_c++

In this article, we implement the concept of callback in C++ and also use gmock as a way to test our code.

OVERVIEW

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.

CASE STUDY

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:

#include <gtest/gtest.h>

#include <gmock/gmock.h>

using ::testing::_;

using ::testing::MockFunction;

This simple example shows how MockFunction can be used in a handy way to mock std::function for testing purposes.

References

[1] https://en.wikipedia.org/wiki/Callback_(computer_programming)

[2] https://en.cppreference.com/w/cpp/utility/functional/function

[3] http://google.github.io/googletest/gmock_cook_book.html#MockFunction

Author:
Cathayoun Ghotbi
C++ Developer at Sigma IT

Never miss a thing With Sigma IT´s newsletter you get all the latest updates on everything we do.

With Sigma IT´s newsletter you get all the latest updates on everything we do.