How to mock an external function in GTest - c++

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

Related

Virtual method in C++ fails to get mocked. What am I missing here?

I have following setup:
Class DataFetcher {
public:
virtual ~DataFetcher() = default;
explicit DataFetcher(const Backends& backends);
virtual vector<Data> GetData(const vector<string>& q) const;
private:
Backends backends_;
};
Implementation:
vector<Data> DataFetcher::GetData(const vector<string>& q) {
cout << "Yikes! This was called";
...
}
Then a piece of function in another place which uses it as:
void Process(const Backends& backends) {
DataFetcher data_fetcher(backends);
...
const auto& data = data_fetcher.GetData(q);
...
}
Now I am trying to test Process with any call to GetData being mocked, as following:
class MockDataFetcher : public DataFetcher {
public:
using DataFetcher::DataFetcher;
MOCK_METHOD(vector<Data>, GetData, (const vector<string>& q), (const, override));
}
class ActualLogicTest : public ... {
protected:
Backends backends_;
}
TEST_F(ActualLogicTest, BasicOne) {
MockDataFetcher mock_data_fetcher(backends_);
vector<Data> data;
ON_CALL(mock_data_fetcher, GetData).WillByDefault(Return(data));
...
Process(backends_);
}
What is wrong in this? I am seeing that actual implementation of GetData is getting called and I am seeing that message Yikes! This was called too. Since GetData is a virtual function, it should get the empty vector of Data back as result from the mocked one. Why is that not happening?
Finally the test crashes because backend doesn't have initialization of its members.
The function doesn't use mock object at all:
void Process(const Backends& backends) {
DataFetcher data_fetcher(backends);
...
const auto& data = data_fetcher.GetData(q);
...
}
Regardless whether you create a MockDataFetcher the Process function create local DataFetcher and uses it - not the mock that you have created in test case - you need to provide it somehow to the Process function.
From your declaration:
virtual vector<Data> GetData(const vector<string>& q) const;
GetData() returns an object.
Yet, in Process(),
void Process(const Backends& backends) {
DataFetcher data_fetcher(backends);
...
const auto& data = data_fetcher.GetData(q); // BUG!! Why is data a reference?
}
The variable 'data' cannot be a reference, since the object it refers to has literally no life span. Any attempt to use 'data' will result in undefined behaviour.

How to use MockSupportPlugin in CppUTest to perform checkExpectations automatically?

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.

How to return const reference to vector item from a mocked method?

I am writing googletest/googlemock-based unit tests for a class using a database object as a dependency, so I decided to mock the database. It provides read-only access to items of type Entry based on an index:
struct Entry {
int x, y;
};
class DbIface {
public:
virtual ~DbIface() {}
virtual int count() const = 0;
virtual const Entry& entry(const int idx) const = 0;
};
class DbMock : public DbIface {
public:
MOCK_CONST_METHOD0(count, int());
MOCK_CONST_METHOD1(entry, const Entry&(const int idx));
};
I want to specify some predefined data for the test and make the mock return that:
const std::vector<Entry> TEST_DATA = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
DbMock mock;
EXPECT_CALL(mock, count).WillOnce(Return(TEST_DATA.size()));
EXPECT_CALL(mock, entry).WillOnce(Invoke([](int i) { return TEST_DATA.at(i); }));
However, I am getting an error on the last EXPECT_CALL:
warning C4172: returning address of local variable or temporary
I expect the GMock-generated wrapper makes a copy from the reference returned by the lambda somewhere along the way, but it's difficult to follow in that mess of code. In any case, how do I achieve what I need without changing the interface?
As clarified by this answer, the type of the TEST_DATA.at(i) expression is Entry, not const Entry&, so the lambda has its return type deduced to be non-reference, causing the problem.
This is fixed by explicitly stating the return type of the lambda:
EXPECT_CALL(mock, entry).WillOnce(Invoke([](int i) -> const Entry& { return TEST_DATA.at(i); }));

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.