How to use MockSupportPlugin in CppUTest to perform checkExpectations automatically? - c++

CppUTest documentations says
MockSupportPlugin makes the work with mocks easier. It does the following work for you automatically:
checkExpectations at the end of every test (on global scope, which goes recursive over all scopes)
clear all expectations at the end of every test
install all comparators that were configured in the plugin at the beginning of every test
remove all comparators at the end of every test
ref: https://cpputest.github.io/plugin_manual.html
I tried the following example:
#include "CppUTest/TestRegistry.h"
#include "CppUTestExt/MockSupportPlugin.h"
MyDummyComparator dummyComparator;
MockSupportPlugin mockPlugin;
mockPlugin.installComparator("MyDummyType", dummyComparator);
TestRegistry::getCurrentRegistry()->installPlugin(&mockPlugin);
with my added MYDummyComparator:
class MyDummyComparator : public MockNamedValueComparator
{
bool isEqual( const void *object1, const void *object2 )
{
return object1 == object2;
}
SimpleString valueToString( const void *object )
{
return SimpleString();
}
} dummyComparator;
But when I remove expectOneCall() or expectNCalls() from my tests, it shows the tests failed. How do I use MockSupportPlugin from CPPUTest to achieve doing "checkExpectations at the end of every test (on global scope, which goes recursive over all scopes)" automatically?

The mock type comparators would be used in your mock comparisons.
For example, you need to compare a struct of type Point, which looks like this:
struct Point {
int x;
int y;
};
You would define your comparator like this:
class PointTypeComparator : public MockNamedValueComparator
{
public:
bool isEqual(const void* object1, const void* object2) override
{
// Casting here the void pointers to the type to compare
const auto *pointObject1 = (const Point *) object1;
const auto *pointObject2 = (const Point *) object2;
// Perform comparison, in this case, comparing x and y
return ((pointObject1->x == pointObject2->x)
&& (pointObject1->y == pointObject2->y);
}
virtual SimpleString valueToString(const void* object)
{
return (char *) "string";
}
};
Next, within you test group, you need to install these comparators in the setup and also in the teardown clear them:
TEST_GROUP(MyTest)
{
void setup()
{
PointTypeComparator pointComparator;
mock().installComparator("Point *", pointComparator); // Note, its a pointer to a Point type
}
void teardown()
{
// Call check expectations here, and also clear all comparators after that
mock().checkExpectations();
mock().clear();
mock().removeAllComparatorsAndCopiers();
}
};
Next, you can use this Comparator, using the withParameterOfType function as:
mock().expectOneCall("foo")
.withParameterOfType("Point *", "name", &address); // Here name is the name of variable, and &address is the address of the Point type variable.

Related

How to mock an external function in GTest

I have a function called tt_init_device(). I have written a TSET_F() test case to verify it.
But inside tt_init_device(), I have an external function wfdEnumerateDevices(NULL, 0, NULL);...I need to mock this function to get return value as true or false...Need help in to do the same.
TEST_F(FusaAppTh,Sample)
{
FusaTelltaleClientAppTh AppThObj(1,"abc");
EXPECT_EQ( WFD_ERROR_NONE,AppThObj.tt_init_device());
}
WFDErrorCode FusaTelltaleClientAppTh::tt_init_device(void)
{
.
.
value = wfdEnumerateDevices(NULL, 0, NULL);
.
.
}
Thanks in advance!
You should create a wrapper for the function that you want to mock. Here is an example.
First you create an interface for the wrapper, then you create two inherited versions. One for production code, which calls the original wfdEnumerateDevices function, and one for testing, which is used for mocking that function.
Here is a sample implementation:
// This is your original function.
int wfdEnumerateDevices(int* p1, int v1, int* p2) { return 0; }
// Create a wrapper interface for it.
class WrapperInterface {
public:
virtual int wfdEnumerateDevices(int* p1, int v1, int* p2) = 0;
};
// An inherited wrapper that calls your original function. Use this for
// your production code.
class ProductionWrapper : public WrapperInterface {
public:
int wfdEnumerateDevices(int* p1, int v1, int* p2) {
return ::wfdEnumerateDevices(p1, v1, p2);
}
};
// An inherited wrapper used only for testing.
class MockWrapper : public WrapperInterface {
public:
MOCK_METHOD(int, wfdEnumerateDevices, (int*, int, int*), (override));
};
class FusaTelltaleClientAppTh {
public:
// Your class should now have a wrapper member which can either be the
// production version for production or the test version for testing.
WrapperInterface* wrapper_;
// Inject the wrapper in constructor.
FusaTelltaleClientAppTh(int v1, std::string s1, WrapperInterface* wrapper)
: wrapper_(wrapper) {}
int tt_init_device(void) {
// Call the wrapper function instead of the original one. Depending on the
// wrapper_ type, either the production or the test version will be
// called.
return wrapper_->wfdEnumerateDevices(nullptr, 0, nullptr);
}
};
// Tests mocking the function to true.
TEST(FusaAppTh, Sample1) {
MockWrapper mockWrapper;
FusaTelltaleClientAppTh AppThObj(1, "abc", &mockWrapper);
ON_CALL(mockWrapper, wfdEnumerateDevices)
.WillByDefault(testing::Return(true));
EXPECT_EQ(1, AppThObj.tt_init_device());
}
// Tests mocking the function to false.
TEST(FusaAppTh, Sample2) {
MockWrapper mockWrapper;
FusaTelltaleClientAppTh AppThObj(1, "abc", &mockWrapper);
ON_CALL(mockWrapper, wfdEnumerateDevices)
.WillByDefault(testing::Return(false));
EXPECT_EQ(0, AppThObj.tt_init_device());
}
Here is a live example: https://godbolt.org/z/vfbKf6oT8

GMock: Match the address of EXPECT_CALL parameter

Is there a way to match the address of a given parameter in an EXPECT_CALL?
I have code like the following:
EXPECT_CALL(mock1, GetTheData()).WillOnce(Return(theData));
EXPECT_CALL(mock2, SetTheData(_)); // How to check the parameter is the same object as the one returned by GetTheData
// the following was tried but does not work
EXPECT_CALL(mock2, SetTheData(_)).WillOnce([&theData](auto param){ EXPECT_EQ(&theData, param) })
But because the SetTheData function takes its argument by value, the address is different. So I would need to find a way to get the object, before it was passed to the SetTheData function.
I tried some stuff with matches, but that did not seem to work either.
Is this possible at all? If so, how? And if not, why not?
EDIT:
As requested here is a more complete example to give more context.
struct TheData
{
// some stl containers
std::unordered_map<int, std::array<std::byte, 16>> mapToArrays;
std::unordered_map<int, long long> mapToInts;
}
class IDataFetcher
{
public:
virtual TheData GetTheData() = 0;
}
class IDataReceiver
{
public:
virtual void SetTheData(TheData theData) = 0;
}
class DataFetcherMock : public IDataFetcher
{
public:
MOCK_METHOD(TheData, GetTheData, (), (override));
}
class DataReceiverMock
{
public:
MOCK_METHOD(void, SetTheData, (TheData), (override));
}
class Sut
{
public:
Sut(std::unique_ptr<IDataFetcher> fetcher, std::unique_ptr<IDataReceiver> receiver)
void DoTheThing()
{
mReceiver->SetTheData(mFetcher->GetTheData());
}
private:
std::unique_ptr<IDataFetcher> mFetcher;
std::unique_ptr<IDataReceiver> mReceiver;
}
TEST(TestFoo, TestGroupFoo)
{
auto fetcherMock = std::make_unique<DataFetcherMock>();
auto receiverMock = std::make_unique<DataReceiverMock>();
EXPECT_CALL(*fetcherMock, GetTheData()).WillOnce(Return(theData));
EXPECT_CALL(*receiverMock, SetTheData(_)); // Here I want to check the objects are the same
Sut sut(std::move(fetcherMock), std::move(receiverMock));
sut.DoTheThing();
}

Get list of functions in a namespace at runtime?

Is it possible to get a list of functions in a certain namespace or all functions in a program at runtime?
I have a function pointer map and I need to add commands on my own to it, but I thought: why not create a namespace and let the program do the work at runtime?
something like(pseudocode):
typedef bool (*command)(void);
namespace Commands
{
bool Start(void)
{
return true;
}
bool End(void)
{
return true;
}
};
std::map<std::string,command> CommandMap;
main()
{
for(each function in namespace Commands)
{
CommandMap[std::string(function_name)] = function;
}
CommandMap["Start"]();
CommandMap["End"]();
return 0;
}
instead of
std::map<std::string,command> CommandMap;
main()
{
CommandMap["Start"] = Commands::Start;
CommandMap["End"] = Commands::End;
//list of thousands of other commands......
CommandMap["Start"]();
CommandMap["End"]();
return 0;
}
Is this possible to achieve in C++ or C++11? Or any alternatives to my goal?
No (it has to be 30 characters).
EDIT: This goes along with my comment about how much control you have. You could redefine all of your functions as functors, and have the constructor register itself with some array. Your base class would look like this:
EDIT2: read the comment about all functions having same arguments and return types, makes it a little cleaner.
class myFunctorBaseClass
{
public:
myFunctorClass () : {//register myself, no duplicates}
virtual int operator () (int);//Whatever types you want
};
class myFunctor: public myFunctorBaseClass //Define as many of these as you need
{
public:
int operator() (int y) { return y; } // Define this as whatever you want
}
This obviously would depend on the objects being constucted, but assuming they all were as an initialization step, this would get you what you want.
NOTE: This may be incomplete/not compile. I just kinda wrote this off the top of my head, but it should be close. The reference you want is "functors" if you have questions about how this works.
Consider something like:
class CommandCollection
{
...
void register_command(Command*, string);
map<string, Command*> m_command_map;
}
class Command
{
...
virtual do_command(...) = 0;
}
class EachCommand : public Command
{
EachCommand() { CommandCollection::instance().register_command(this, my_name); }
...
virtual do_command(...);
}
EachCommand each_command_inst;
The Command base class has a virtual to do a command. Each derived type implements the command (you could try overloading the () operator to make them look more like functions).
Each derived Command registers itself with the CommandCollection, so it can be known in a central location. If you want to associate the commands by string (seems good if a user is typing them in), then that would be the key in the map.
As mentioned elsewhere, names (in C and C++, other languages may/do differ on this point) only really exist as part of the source-code. Once compiled, the names cease to have any meaning in C and C++.
One could, however, consider some sort of structure like this:
class CommandBase
{
virtual bool doCommand() = 0;
virtual std::string name() = 0;
virtual ~CommandBase() {}
};
class StartCommand : public CommandBase
{
bool doCommand() { ...; return true }
std::string name() { return "Start"; }
};
void RegisterCommand(CommandBase *cmd)
{
CommandMap[cmd->name] = cmd;
}
...
StartCommand start;
...
void someFunction()
{
RegisterCommand(&start);
}
I'll probably get a downvote for mentioning macros, because these are evil - don't use this if you are a purist that don't like macros.
#define CMD(x) CommandMap[#x] = Command::x
CMD(start);
CMD(end);
There are certainly other variants, and someone who knows templates may well come up with something that does this using templates.

Recasting const function

I'm using a library (libtcod) that has an A* pathfinding algorithm. My class inherits the callback base class, and I implement the required callback function. Here is my generic example:
class MyClass : public ITCODPathCallback
{
...
public: // The callback function
float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const
{
return this->doSomeMath();
};
float doSomeMath() { // non-const stuff }
};
I found a number of examples using const_cast and static_cast, but they seemed to be going the other way, making a non-const function be able to return a const function result. How can I do it in this example?
getWalkCost() is defined by my library that I cannot change, but I want to be able to do non-const things in it.
The best solution depends on why you want to do non-const stuff. For example, if you have a cache of results that you want to use to improve performance, then you can make the cache be mutable, since that preserves the logical constness:
class MyClass : public ITCODPathCallback
{
...
public: // The callback function
float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const
{
return this->doSomeMath();
};
float doSomeMath() const { // ok to modify cache here }
mutable std::map<int,int> cache;
};
Or perhaps you want to record some statistics about how many times the getWalkCost was called and what the maximum x value was, then passing a reference to the statistics may be best:
class MyClass : public ITCODPathCallback
{
...
public:
struct WalkStatistics {
int number_of_calls;
int max_x_value;
WalkStatistics() : number_of_calls(0), max_x_value(0) { }
};
MyClass(WalkStatistics &walk_statistics)
: walk_statistics(walk_statistics)
{
}
// The callback function
float getWalkCost(int xFrom, int yFrom, int xTo, int yTo, void *userData ) const
{
return this->doSomeMath();
};
float doSomeMath() const { // ok to modify walk_statistics members here }
WalkStatistics &walk_statistics;
};
You can hack it this way:
return const_cast<MyClass*>(this)->doSomeMath();
Of course this won't be considered good design by most people, but hey. If you prefer you can instead make doSomeMath() const, and mark the data members it modifies as mutable.

raw function pointer from a bound method

I need to bind a method into a function-callback, except this snippet is not legal as discussed in demote-boostfunction-to-a-plain-function-pointer.
What's the simplest way to get this behavior?
struct C {
void m(int x) {
(void) x;
_asm int 3;
}};
typedef void (*cb_t)(int);
int main() {
C c;
boost::function<void (int x)> cb = boost::bind(&C::m, &c, _1);
cb_t raw_cb = *cb.target<cb_t>(); //null dereference
raw_cb(1);
return 0;
}
You can make your own class to do the same thing as the boost bind function. All the class has to do is accept the function type and a pointer to the object that contains the function. For example, this is a void return and void param delegate:
template<typename owner>
class VoidDelegate : public IDelegate
{
public:
VoidDelegate(void (owner::*aFunc)(void), owner* aOwner)
{
mFunction = aFunc;
mOwner = aOwner;
}
~VoidDelegate(void)
{}
void Invoke(void)
{
if(mFunction != 0)
{
(mOwner->*mFunction)();
}
}
private:
void (owner::*mFunction)(void);
owner* mOwner;
};
Usage:
class C
{
void CallMe(void)
{
std::cout << "called";
}
};
int main(int aArgc, char** aArgv)
{
C c;
VoidDelegate<C> delegate(&C::CallMe, &c);
delegate.Invoke();
}
Now, since VoidDelegate<C> is a type, having a collection of these might not be practical, because what if the list was to contain functions of class B too? It couldn't.
This is where polymorphism comes into play. You can create an interface IDelegate, which has a function Invoke:
class IDelegate
{
virtual ~IDelegate(void) { }
virtual void Invoke(void) = 0;
}
If VoidDelegate<T> implements IDelegate you could have a collection of IDelegates and therefore have callbacks to methods in different class types.
Either you can shove that bound parameter into a global variable and create a static function that can pick up the value and call the function on it, or you're going to have to generate per-instance functions on the fly - this will involve some kind of on the fly code-gen to generate a stub function on the heap that has a static local variable set to the value you want, and then calls the function on it.
The first way is simple and easy to understand, but not at all thread-safe or reentrant. The second version is messy and difficult, but thread-safe and reentrant if done right.
Edit: I just found out that ATL uses the code generation technique to do exactly this - they generate thunks on the fly that set up the this pointer and other data and then jump to the call back function. Here's a CodeProject article that explains how that works and might give you an idea of how to do it yourself. Particularly look at the last sample (Program 77).
Note that since the article was written DEP has come into existance and you'll need to use VirtualAlloc with PAGE_EXECUTE_READWRITE to get a chunk of memory where you can allocate your thunks and execute them.
#include <iostream>
typedef void(*callback_t)(int);
template< typename Class, void (Class::*Method_Pointer)(void) >
void wrapper( int class_pointer )
{
Class * const self = (Class*)(void*)class_pointer;
(self->*Method_Pointer)();
}
class A
{
public:
int m_i;
void callback( )
{ std::cout << "callback: " << m_i << std::endl; }
};
int main()
{
A a = { 10 };
callback_t cb = &wrapper<A,&A::callback>;
cb( (int)(void*)&a);
}
i have it working right now by turning C into a singleton, factoring C::m into C::m_Impl, and declaring static C::m(int) which forwards to the singleton instance. talk about a hack.