It's a simple example to use google mocking along with fixtures. I am trying to setup up and learn google mock on Xcode and wrote following code
using ::testing::Return;
class Shape {
public:
virtual int calculateArea() = 0;
virtual std::string getShapeColor() = 0; // this interface must have been used by some other class under test
};
// Mock class for Shape
class MockShape : public Shape{
public:
MOCK_METHOD0(calculateArea, int());
MOCK_METHOD0(getShapeColor, std::string());
};
// class under test
class Show{
public:
Show() : printFlag(false), isColorValid(false) {}
void printArea(Shape *shape) {
if (shape->calculateArea() <= 0)
printFlag = false;
else
printFlag = true;
}
void printColor(Shape *shape) {
if (shape->getShapeColor().compare("black"))
isColorValid = true;
else
isColorValid = false;
}
bool printFlag;
bool isColorValid;
};
// Test fixture for class under test
class FixtureShow : public ::testing::Test{
public:
void SetUp(){}
void TearDown(){}
void SetUpTestCase(){}
void TearDownTestCase(){}
Show show; // common resources to be used in all the test cases
MockShape mockedShape;
};
TEST_F(FixtureShow, areaValid) {
EXPECT_CALL(mockedShape, calculateArea()).WillOnce(Return(5));
show.printArea(&mockedShape);
EXPECT_EQ(show.printFlag, true);
}
"TEST_F(FixtureShow, areaValid) " is giving error "Call to non static member function without an object argument". Can anyone help me why am I getting this error?
SetUpTestCase() and TearDownTestCase() are meant to be declared as static member functions. You can also delete them unless you are planning to put some code in.
Related
I have implemented a Dependency Injection pattern in my code. I did that to be able to mock a service using gmock. The DI implementation works in production code, however, I am having trouble with my test setup. When using the EXPECT_CALL macro, I get "expression must have class type" error. I believe this is related to the way I designed the dependency, but I can't find an alternative solution (lack of experience). I have browsed previous threads on similar issues, but none helped. Would you be kind to take a look at the code below and hint possible workarounds (simplified code example using a Car-Engine interface)?
// Engine interface class with pure virtual functions
class IEngine
{
public:
virtual ~IEngine() = default;
virtual void start() = 0;
virtual void stop() = 0;
};
// A V8Engine class implementing this interface
class V8Engine : public IEngine
{
public:
void start() override { std::cout << "V8 Engine started\n"; };
void stop() override { std::cout << "V8 Engine stopped\n"; };
};
// Car.h file
class Car
{
public:
Car(IEngine *engineService);
void Drive();
private:
IEngine* mEngine = nullptr;
};
// Car.cpp file
Car::Car(IEngine* engineService)
: mEngine(engineService)
{
if (mEngine == nullptr)
{
throw std::invalid_argument("service must not be null");
}
}
void Car::Drive()
{
mEngine->start();
mEngine->stop();
}
I would like to be able to mock the engine implementation and instead of using a "real V8Engine", utilize the mock. Here is how I set up my test:
class MockEngine : public IEngine
{
public:
MOCK_METHOD(void, start, (), (override));
MOCK_METHOD(void, stop, (), (override));
};
TEST(TestCarClass, TestCarWithMockEngine)
{
IEngine *mockEngine = new MockEngine;
Car carUnderTest(mockEngine);
carUnderTest.Drive();
EXPECT_CALL(mockEngine, start()); // This is the part where I get the error due to invalid mockEngine setup
}
EXPECT_CALL expects mock object as first parameter, you pass reference to mock.
either use *mockEngine:
TEST(TestCarClass, TestCarWithMockEngine)
{
IEngine *mockEngine = new MockEngine;
Car carUnderTest(mockEngine);
EXPECT_CALL(*mockEngine, start());
carUnderTest.Drive();
}
or avoid allocation directly:
TEST(TestCarClass, TestCarWithMockEngine)
{
MockEngine mockEngine;
Car carUnderTest(&mockEngine);
EXPECT_CALL(mockEngine, start());
carUnderTest.Drive();
}
I'm trying to write a unittest but I'm running into some problems.
I've got a class which has an int to keep track of the current state. All classes that are inherited of this class can change the state by calling the protectedFunction.
class RandomClass
{
public:
RandomClass()
{
mState = 0;
}
protected:
void protectedFunction()
{
++mState;
}
private:
int mState;
friend void UNITTEST_setMState(int state);
friend int UNITTEST_getMState();
};
Now i'd like to write a unittest for this class. So I created a new class which inherits the previous class. To Properly test all the states I need to set the state, and I need to get the state to assert it. I've tried using a friend function but it does not seem to work.
class UnittestRandomClass : public RandomClass
{
public:
void wrapperProtectedFunction()
{
protectedFunction();
}
void UNITTEST_setMState(int state)
{
this->mState = state; // Apparently not like this
}
int UNITTEST_getMState()
{
return this->mState; // Apparently not like this
}
};
int main() {
UnittestRandomClass ut;
ut.UNITTEST_setMState(1);
ut.wrapperProtectedFunction();
int res = ut.UNITTEST_getMState();
ASSERT_EQ(res, 2);
}
I seem to be doing something wrong, as the mState still appears to be private and thus I'm getting an inaccessible error. I've also tried calling it directly by just returning mState, but the same error applies.
One solution would be to move the mState to protected, but as there are other classes which inherit the RandomClass, I do not think that would be a save solution.
So how would I be able to solve such an issue and resolve my errors?
For future viewers here is the working code:
class RandomClass
{
public:
RandomClass()
{
mState = 0;
}
void publicFunction();
protected:
void protectedFunction()
{
++mState;
}
private:
int mState;
friend class UnittestRandomClass;
};
class UnittestRandomClass : public RandomClass
{
public:
void wrapperProtectedFunction()
{
protectedFunction();
}
void setMState(int state)
{
mState = state;
}
int getMState()
{
return mState;
}
};
int main() {
UnittestRandomClass ut;
ut.setMState(1);
ut.wrapperProtectedFunction();
int res = ut.getMState();
ASSERT_EQ(res, 2);
}
Your class declares a free-standing function to be friend.
Your unit test uses a member function of a class, the class is not declared friend.
You can write friend class UnitTestRandomClass;
Specifically, what you want to do, make a member function of a future derived class a friend is not provided by the standard. There is no syntax for that.
I'm still pretty new to Google Mock so learning as I go. I've just been adding some unit tests and I've run into an issue where I can't get ON_CALL() to correctly stub a method called from within a method.
The following code outlines what I have;
class simpleClass
{
public:
bool simpleFn1() { return simpleFn2(); }
virtual bool simpleFn2() { return FALSE; }
}
In my unit test I have:
class simpleClassMocked : public simpleClass
{
private:
MOCK_METHOD0(simpleFn2, bool());
}
class simpleClassTests : public ::testing::Test
{
}
TEST_F(simpleClassTests, testSimpleFn2)
{
shared_ptr<simpleClassMocked> pSimpleClass = shared_ptr< simpleClassMocked >(new simpleClassMocked());
ON_CALL(*pSimpleClass, simpleF2()).WillByDefault(Return(TRUE));
// This works as expected - simpleFn2() gets stubbed
pSimpleClass->simpleFn2();
// This doesn't work as expected - when simpleFn1 calls simpleFn2 it's not the stubbed expectation???
pSimpleClass->simpleFn1();
}
I figure I must be missing something obvious here, can anyone help? Thanks!
you'll have to Mark the method as virtual and add a corresponding MOCK function in the simpleClassMocked class
class simpleClass
{
public:
virtual bool simpleFn1() { return simpleFn2(); }
virtual bool simpleFn2() { return FALSE; }
}
Also, you need to put the Mock methods in the public area
class simpleClassMocked : public simpleClass
{
public:
MOCK_METHOD0(simpleFn2, bool());
MOCK_METHOD0(simpleFn1, bool());
}
It will work now
I am encountering a very strange issue in my code... I've spent now a whole afternoon and cannot get nor heads nor tails on it. But maybe someone here can point me what I'm doing wrong.
So for the explanation:
I have a DLL.
In it I have 2 classes:
class Plugin {
public:
Plugin() : isInited(false) { all_plugins.push_back(this); }
virtual ~Plugin() { }
virtual int OnInit(ONINIT_PARAMS) { return 0; }
virtual void OnDeInit(ONDEINIT_PARAMS) { }
virtual int OnTick(ONTICK_PARAMS) { return 0; }
private:
static std::vector<Plugin*> all_plugins;
private: // NO COPY CLASS
Plugin(const Plugin&);
const Plugin& operator=(const Plugin&);
};
This class is responsible for mapping the Init/DeInit/Tick function-calls which comes from the main application.
Secondly I have this:
class DynamicModule {
public:
DynamicModule() : isLoaded(false) { all_modules.push_back(this); }
virtual ~DynamicModule() { }
virtual int OnLoad() { return 0; };
virtual int OnUnload() { return 0; };
private:
static std::vector<DynamicModule*> all_modules;
private: // NO COPY CLASS
DynamicModule(const DynamicModule&);
const DynamicModule& operator=(const DynamicModule&);
};
#define IMPLEMENT_DYNAMICMODULE std::vector<DynamicModule*> DynamicModule::all_modules;
Now in plugin.cpp I do:
IMPLEMENT_DYNAMICMODULE;
std::vector<Plugin*> Plugin::all_plugins;
That takes care of the static stuff.
Now I define a class (in a header file):
class InMarket : public Plugin {
public:
int OnInit (ONINIT_PARAMS);
void OnDeInit(ONDEINIT_PARAMS);
int OnTick (ONTICK_PARAMS);
private:
};
And implement it in a C++ file:
static class InMarket _InMarket;
I traced it, and the constructor gets called correctly. And inserted into Plugin::all_plugins.
Then I continue tracing, and I see the modules (2 at the moment, defined for example like the next example [in a C++ file]):
static class MQL4Trade : public DynamicModule {
public:
virtual int OnLoad() {
__OrderSend = (_OrderSend)GetProcAddress(exe, "OrderSend");
__OrdersCount = (_OrdersCount)GetProcAddress(exe, "OrdersCount");
return 0;
}
} _MQL4Trade;
I see these modules get inserted as well nicely in DynamicModule::all_modules.
But at the same time when I see this, I also noticed the Plugin::all_plugins has a {size=0}?!
Then when I enter my OnInit() function, I see that all_modules has a size of 2, and all_plugins = 0. Even though ALL of the constructors had been called?
I load my library as:
HMODULE plugin = LoadLibrary(pluginFilename.c_str());
All static objects constructors are called....
And I don't see ANY differences between the 2 things.
What is going on here?
I've recently returned to C++ development after a hiatus, and have a question regarding
implementation of the State Design Pattern. I'm using the vanilla pattern, exactly as
per the GoF book.
My problem is that the state machine itself is based on some hardware used as part of
an embedded system - so the design is fixed and can't be changed. This results in a
circular dependency between two of the states (in particular), and I'm trying to
resolve this. Here's the simplified code (note that I tried to resolve this by using
headers as usual but still had problems - I've omitted them in this code snippet):
#include <iostream>
#include <memory>
using namespace std;
class Context
{
public:
friend class State;
Context() { }
private:
State* m_state;
};
class State
{
public:
State() { }
virtual void Trigger1() = 0;
virtual void Trigger2() = 0;
};
class LLT : public State
{
public:
LLT() { }
void Trigger1() { new DH(); }
void Trigger2() { new DL(); }
};
class ALL : public State
{
public:
ALL() { }
void Trigger1() { new LLT(); }
void Trigger2() { new DH(); }
};
// DL needs to 'know' about DH.
class DL : public State
{
public:
DL() { }
void Trigger1() { new ALL(); }
void Trigger2() { new DH(); }
};
class HLT : public State
{
public:
HLT() { }
void Trigger1() { new DH(); }
void Trigger2() { new DL(); }
};
class AHL : public State
{
public:
AHL() { }
void Trigger1() { new DH(); }
void Trigger2() { new HLT(); }
};
// DH needs to 'know' about DL.
class DH : public State
{
public:
DH () { }
void Trigger1() { new AHL(); }
void Trigger2() { new DL(); }
};
int main()
{
auto_ptr<LLT> llt (new LLT);
auto_ptr<ALL> all (new ALL);
auto_ptr<DL> dl (new DL);
auto_ptr<HLT> hlt (new HLT);
auto_ptr<AHL> ahl (new AHL);
auto_ptr<DH> dh (new DH);
return 0;
}
The problem is basically that in the State Pattern, state transitions are made by
invoking the the ChangeState method in the Context class, which invokes the
constructor of the next state.
Because of the circular dependency, I can't invoke the constructor because it's
not possible to pre-define both of the constructors of the 'problem' states.
I had a look at this article, and the template method which seemed to be the ideal solution - but it doesn't compile and my knowledge of templates is a rather limited...
The other idea I had is to try and introduce a Helper class to the subclassed states,
via multiple inheritance, to see if it's possible to specify the base class's constructor
and have a reference to the state subclasse's constructor. But I think that was rather
ambitious...
Finally, would a direct implmentation of the Factory Method Design Pattern be the best way
to resolve the entire problem?
You can define the member functions outside of the class definitions, e.g.,
class DL : public State
{
public:
void Trigger2();
};
inline void DL::Trigger2() { new DH(); }
Define the member functions that rely on later class definitions after those classes are defined. The inline keyword is only necessary if you define the member function outside of the class in the header file.
As an aside, why are you just using new DH() in your functions; you're leaking memory everywhere!