Implementing and Testing Callbacks in C++ and gmock - Holisticon
Skip to content
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 callback concept in C++ and test our code using gmock.

OVERVIEW

Callbacks exist in real life: you call someone, and they cannot answer at that moment for any reason, you request a callback so that they call you later. 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 that 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 Holisticon Connect

Passion And Execution

Who We Are

At Holisticon Connect, our core values of Passion and Execution drive us toward a Promising Future. We are a hands-on tech company that places people at the centre of everything we do. Specializing in Custom Software Development, Cloud and Operations, Bespoke Data Visualisations, Engineering & Embedded services, we build trust through our promise to deliver and a no-drama approach. We are committed to delivering reliable and effective solutions, ensuring our clients can count on us to meet their needs with integrity and excellence. 

Innovation is a Process.

Send us a message and we’ll get back to you as soon as possible.

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

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