Reputation: 45
I'm trying to test a class using the google mock framework and can't figure out how to execute my test.
Here is my simplified code:
I have an interface in a .h file:
namespace Mynamespace
{
class IMyInterface
{
public:
virtual ~ IMyInterface() {};
virtual int myFunction() = 0;
};
}
and my mock class which inherits from the interface:
#include <gmock/gmock.h>
#include <IMyInterface.h>
namespace testing
{
class MyClassMock : public IMyInterface
{
public:
~ MyClassMock();
MyClassMock();
MOCK_METHOD0(myFunction, int());
};
}
with the implementation of the mock class:
#include "MyClassMock.h"
namespace testing
{
MyClassMock:: MyClassMock()
{
}
MyClassMock::~ MyClassMock()
{
}
}
my other class takes an object of MyClass as an argument of a function like this:
#include "MyClass.h"
namespace Mynamespace
{
class AnotherClass
{
public:
AnotherClass();
~ AnotherClass();
void anotherFunction(MyClass&);
};
}
with the implementation:
#include MyClass.h
#include AnotherClass.h
namespace Mynamespace
{
AnotherClass:: AnotherClass()
{
}
AnotherClass::~ AnotherClass()
{
}
AnotherClass::anotherFunction(MyClass& obj_myClass)
{
//does something...
}
}
I would then like to test the function of AnotherClass using a mock like this:
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "MyClass.h"
#include "MyClassMock.h"
#include "AnotherClass.h"
using namespace testing;
using namespace std;
TEST(DirectivityParameter, CanInstantiate)
{
AnotherClass obj_anotherClass;
MyClassMock mock_myClass;
EXPECT_CALL(mock_myClass, myFunction())
.Times(1)
.WillOnce(Return(0));
obj_anotherClass.anotherFunction(&mock_myClass);
}
This produces the semantic issue: "Non-const lvalue reference to type 'MyClass' cannot bind to a temporary of type 'MyClasssMock *'
I'm confused because I thought the purpose of MyClassMock is to emulate MyClass, but this messages tells me otherwise.
What am I doing wrong? Any help would be very much appreciated!
cheers, Simon
Upvotes: 0
Views: 3088
Reputation: 774
You should implement IMyInterface
in your class MyClass
something like below
class MyClass :IMyInterface
{
public:
virtual int myFunction();
}
And you should pass IMyInterface
to in your AnotherClass
function syntax would be something like below :
class AnotherClass
{
public:
AnotherClass();
~ AnotherClass();
void anotherFunction(IMyInterface *);
};
then you can test your AnotherClass using your test code
AnotherClass obj_anotherClass;
MyClassMock mock_myClass;
EXPECT_CALL(mock_myClass, myFunction())
.Times(1)
.WillOnce(Return(0));
obj_anotherClass.anotherFunction(&mock_myClass);
Upvotes: 3