Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NiceMock as instance variable with GoogleMock

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?

like image 545
maria90 Avatar asked Jun 26 '12 09:06

maria90


1 Answers

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.

like image 190
Jens Ehrlich Avatar answered Sep 20 '22 16:09

Jens Ehrlich