Using NiceMock as instance variable with GoogleMock - c++

I want to assign a NiceMock with the return value of a method. The NiceMock is an instance variable.
class TestFileToOsg : public testing::Test
{
public:
NiceMock<MockFileToOsg>* _mockFileToOsg;
protected:
virtual void SetUp();
};
void TestFileToOsg::SetUp()
{
_mockFileToOsg = FixtureFileToOsg::getMockFileToOsgWithValidConfig();
}
The fixture method is:
MockFileToOsg* FixtureFileToOsg::getMockFileToOsgWithValidConfig()
{
MockFileToOsg* fileToOsg = new MockFileToOsg(...);
return fileToOsg;
}
The compiler throws the following error:
error: invalid conversion from ‘MockFileToOsg*’ to ‘testing::NiceMock<MockFileToOsg>*’
How can I assign the instance variable with the return value of the fixture method?

In your testclass you should only have a pointer to your mockobject:
class TestFileToOsg : public testing::Test
{
public:
MockFileToOsg* _mockFileToOsg;
protected:
...
Your fixture should instantiate a NiceMock and return a pointer to your mockobject.
MockFileToOsg* FixtureFileToOsg::getMockFileToOsgWithValidConfig()
{
MockFileToOsg* fileToOsg = new NiceMock<MockFileToOsg>(...);
return fileToOsg;
}
The NiceMock<> derives from the mockClass.So NiceMock<> must only be used when you instantiate a MockObject.

Related

How to Mock the return object

I try to mock a User class and its nested struct UserBuilder:
class User
{
public:
virtual int loadData(const std::string& filename);
virtual UserBuilder getUserBuilder(const std::string& functionName) const;
struct UserBuilder
{
UserBuilder(std::string functionName) : m_functionName{functionName} {};
virtual ~UserBuilder();
virtual UserBuilder& fun1();
virtual UserBuilder& fun2(int32_t num);
virtual bool callFunction();
private:
std::string m_functionName{};
};
}
This is the mock class for User:
class UserMock : public User
{
public:
MOCK_METHOD1(loadData, int(const std::string& filename));
MOCK_CONST_METHOD1(getUserBuilder, UserBuilder(const std::string& functionName));
};
Thsi is the mock class for UserBuilder:
struct UserBuilderMock : public User::UserBuilder
{
public:
UserBuilderMock(std::string functionName) : User::UserBuilder(functionName) {}
MOCK_METHOD0(fun1, UserBuilder&());
MOCK_METHOD1(fun2, UserBuilder&(int32_t num));
MOCK_METHOD0(callFunction, bool());
};
I want to test this function:
void useCase(std::unique_ptr<User> userP)
{
int status = userP->loadFile("init");
if (status == 0)
{
User::UserBuilder builder = userP->getUserlBuilder("init");
bool result = builder.fun1().fun2(1).callFunction();
return result;
}
else
{
return false;
}
}
I give the getUserBuilder("init") a mock object builderMock as its return value, like this:
auto userMock = std::make_unique<UserMock>();
ON_CALL(*userMock, loadFile("init")).WillByDefault(Return(0));
UserBuilderMock builderMock("init");
EXPECT_CALL(*userMock, getUserBuilder("init")).WillOnce(ReturnPointee(&builderMock));
EXPECT_CALL(builderMock,fun1()).Times(1);
The test log fail: fun1 never called-unsatisfied and active.
I want to use the builderMock object to call the mock method fun1,fun2 and callFunction, but it still use the real UserBuilder object
call the real fun1,fun2 and callFunction. What should I do to make it use Mock object call the Mock method?
You have to rewrite your code to make User::getUserBuilder return a pointer (possibly smart one) to UserBuilder.
With the method returning UserBuilder object
EXPECT_CALL(*userMock, getUserBuilder("init")).WillOnce(ReturnPointee(&builderMock));
getUserBuilder casts the mock to an object of its base class (slicing), losing all the the mock additions.

TEST_F in google mock giving error

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.

C++ Google Mock - EXPECT_CALL() - expectation not working when not called directly

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

Fails to allocate derivative class to base class pointer?

I have a AbstractFactory, WinFactory and IOSFactory classes.
AbstactFactory inheritences WinFactory and IOSFactory as the following:
class IOSFacetory {
private:
IOSRectButton *_rectbtn;
IOSCircularButton *_circbtn;
public:
IOSFacetory() : _rectbtn(NULL), _circbtn(NULL) {} // set rectbtn to null
IOSRectButton* getIOSRectBtn () {
if(!_rectbtn) _rectbtn = new IOSRectButton;
return _rectbtn;
}
IOSCircularButton* getIOSCircBtn() {
if(!_circbtn) _circbtn = new IOSCircularButton;
return _circbtn;
}
~IOSFacetory() {
if(_rectbtn) delete _rectbtn;
if(_circbtn) delete _circbtn;
}
};
class WinFacetory {
private:
WinRectButton *_rectbtn;
WinCircularButton *_circbtn;
public:
WinFacetory() : _rectbtn(NULL), _circbtn(NULL) {} // set rectbtn to null
WinRectButton* getWinRectBtn () {
if(!_rectbtn) _rectbtn = new WinRectButton;
return _rectbtn;
}
WinCircularButton* getWinCircBtn() {
if(!_circbtn) _circbtn = new WinCircularButton;
return _circbtn;
}
~WinFacetory() {
if(_rectbtn) delete _rectbtn;
if(_circbtn) delete _circbtn;
}
};
class AbstractFactory : public WinFacetory, public IOSFacetory {
public:
AbstractFactory(){}
};
in the main function, I'm trying to set a IOSFactory into a AbstractFactory Pointer:
#include "AbstractFactory.h"
int main() {
#ifdef _WIN
AbstractFactory* factory = new WinFacetory;
#else
AbstractFactory* factory = new IOSFacetory;
#endif
std::cin.get();
return 0;
}
It doesn't work and I get the following compilation error:
IntelliSense: a value of type "IOSFacetory *" cannot be used to initialize an entity of type "AbstractFactory *.
I guess I have a minor error but I can't figure it out. I'd like to get helped. thanks!
You should reverse your inheritance relations. AbstractFactory should be a base class of both IOSFactory and WinFactory.
Remember to declare a virtual destructor in the base class.
You should derive WinFacetory and IOSFacetory from AbstractFactory. Now you do it contrariwise.

How to declare factory-like method in base class?

I'm looking for solution of C++ class design problem. What I'm trying to achieve is having static method method in base class, which would return instances of objects of descendant types. The point is, some of them should be singletons. I'm writing it in VCL so there is possibility of using __properties, but I'd prefer pure C++ solutions.
class Base {
private:
static Base *Instance;
public:
static Base *New(void);
virtual bool isSingleton(void) = 0;
}
Base::Instance = NULL;
class First : public Base { // singleton descendant
public:
bool isSingleton(void) { return true; }
}
class Second : public Base { // normal descendant
public:
bool isSingleton(void) { return false; }
}
Base *Base::New(void) {
if (isSingleton())
if (Instance != NULL)
return Instance = new /* descendant constructor */;
else
return Instance;
else
return new /* descendant constructor */;
}
Arising problems:
how to declare static variable Instance, so it would be static in descendant classes
how to call descendant constructors in base class
I reckon it might be impossible to overcome these problems the way I planned it. If so, I'd like some advice on how to solve it in any other way.
Edit: some minor changes in code. I have missed few pointer marks in it.
Just to check we have our terminologies in synch - in my book, a factory class is a class instances of which can create instances of some other class or classes. The choice of which type of instance to create is based on the inputs the factory receives, or at least on something it can inspect. Heres's a very simple factory:
class A { ~virtual A() {} };
class B : public A {};
class C : public A {};
class AFactory {
public:
A * Make( char c ) {
if ( c == 'B' ) {
return new B;
}
else if ( c == 'C' ) {
return new C;
}
else {
throw "bad type";
}
}
};
If I were you I would start again, bearing this example and the following in mind:
factorioes do not have to be singletons
factories do not have to be static members
factories do not have to be members of the base class for the hierarchies they create
factory methods normally return a dynamically created object
factory methods normally return a pointer
factory methods need a way of deciding which class to create an instance of
I don't see why your factory needs reflection, which C++ does not in any case support in a meaningful way.
Basing this on the answer by #Shakedown, I'll make Base be templated on the actual type, using the CRTP:
template <class T>
class Base
{
public:
static std::auto_ptr<Base<T> > construct()
{
return new T();
}
};
class First : public Base<First>
{
};
class Second : public Base<Second>
{
};
This is nice because construct is now once again a static member. You would call it like:
std::auto_ptr<First> first(First::construct());
std::auto_ptr<Second> second(Second::construct());
// do something with first and second...
You can create a Singleton class and a NonSingleton class, and make all the descendants inherit one of them.
class Base {
public:
static Base *New() = 0;
}
class SingletonDescendant: public Base {
public:
*Base::New() {
if (Instance != NULL)
return Instance = new /* descendant constructor */;
else
return Instance;
}
private:
static Base *Instance;
}
SingletonDescendant::Instance = NULL;
class NonSingletonDescendant: public Base {
public:
*Base::New() {
return new;
}
}
class First : public SingletonDescendant{ // singleton descendant
}
class Second : public NonSingletonDescendant{ // normal descendant
}
It solves the issues that you raised:
How to declare static variable Instance, so it would be static in descendant classes: It exists only in the SingletonDescendant class.
How to call descendant constructors in base class: Using the New function
I have to write construct() method in every descendant; I consider it redundant, as it is obvious what it has to do: Now it is only in SingletonDescendant and NonSingletonDescendant.
How about something like this:
class Base
{
public:
virtual Base construct() = 0;
};
class First : public Base
{
public:
Base construct(){ return First(); // or whatever constructor }
};
class Second : public Base
{
public:
Base construct(){ return Second(...); // constructor }
};