#ifndef __TESTLISTENERBASE_H__
#define __TESTLISTENERBASE_H__
#include <unordered_set>
#include <string>
class TestListenerBase
{
protected:
void AddMethodCall(std::string methodName)
{
_methodsCalled.insert(methodName);
}
bool WasCalled(std::string methodName)
{
return _methodsCalled.count(methodName) > 0;
}
private:
std::unordered_set<std::string> _methodsCalled;
};
#define REGISTER_METHOD(METHODNAME) \
void METHODNAME () override\
{ \
AddMethodCall(#METHODNAME); \
} \
bool METHODNAME##WasCalled() \
{ \
return WasCalled(#METHODNAME); \
}
#endif
#ifndef __MY_CLASS_MOCK__
#define __MY_CLASS_MOCK__
#include "TestListenerBase.h"
#include "MyClass.h"
class MyClassMock : public MyClass, public TestListenerBase
{
public:
REGISTER_METHOD(DoSomething);
};
#endif
#include "stdafx.h"
#include <memory>
#include "MyClassMock.h"
int _tmain(int argc, _TCHAR* argv[])
{
MyClassMock mock;
bool result = mock.DoSomethingWasCalled(); // return false
mock.DoSomething();
result = mock.DoSomethingWasCalled(); // result true
return 0;
}
Labels: C++, Mock objects