Over a million developers have joined DZone.

Simple Mocking in C++

· DevOps Zone

Discover how to optimize your DevOps workflows with our cloud-based automated testing infrastructure, brought to you in partnership with Sauce Labs

I’ve been working in C++ for a few months now – after three years we’ve been apart.
I always amazes me how simple things I took for granted do not exist (at least not out of the box) in C++, one of which are reflection.

Two weeks ago I needed to make sure that a method was called in a test, I could have used Google’s mocking framework but I needed simpler and quicker solution. I just wanted to know in a specific point at the test if a method was called.

Although C++ does not have reflection it does have macros (i.e. #Define) and I’ve utilized the C++ macros to create the following class:

#include <unordered_set>
#include <string>
class TestListenerBase
    void AddMethodCall(std::string methodName)
    bool WasCalled(std::string methodName)
        return _methodsCalled.count(methodName) > 0;
    std::unordered_set<std::string> _methodsCalled;
    void METHODNAME () override\
    { \
        AddMethodCall(#METHODNAME); \
    } \
    bool METHODNAME##WasCalled() \
    { \
        return WasCalled(#METHODNAME); \

By inheriting from the class above I could define the “mocked” methods, each method would have another method  auto-generated so I can test if the method was called.

#ifndef __MY_CLASS_MOCK__
#define __MY_CLASS_MOCK__
#include "TestListenerBase.h"
#include "MyClass.h"
class MyClassMock : public MyClass, public TestListenerBase

Using this solution I needed to declare each method, the good news is that renaming the method would cause the mocked method name to change as well.

Using the new "mock object" is a simple as writing code:

#include "stdafx.h"
#include <memory>
#include "MyClassMock.h"
int _tmain(int argc, _TCHAR* argv[])
    MyClassMock mock;
    bool result = mock.DoSomethingWasCalled(); // return false
    result = mock.DoSomethingWasCalled(); // result true
    return 0;

That’s it – it’s not perfect but it works.

In case you like parameters in your method you’ll have to improve this example – it’s not hard and I know you’re up to the task.

Happy coding…

Download “The DevOps Journey - From Waterfall to Continuous Delivery” to learn learn about the importance of integrating automated testing into the DevOps workflow, brought to you in partnership with Sauce Labs.


Published at DZone with permission of Dror Helper, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}