fhnaseer
fhnaseer

Reputation: 7267

Google Mock Help Required,

I have 2 classes.

class SomeClass
{
public:
    int SomeFunction()
    {
        return 5;
    }
};


class AnotherClass
{
public:
    int AnotherFunction(SomeClass obj)
    {
        return obj.SomeFunction();
    }
};

I have made a mock class for SomeClass.

class MockSomeClass : public SomeClass
{
public:
    MOCK_METHOD0(SomeFunction, int());
};

Now I want in unit test that when i call AnotherClass.AnotherFunction i get result of my own choice. AnotherFunction uses function of SomeClass.SomeFunction(). I have mocked SomeClass. And I have set that when function of mocked object calls it returs 10. But when i run unit test it returns 5 (origional function). What should i do. Below is the unit test which i have written.

[TestMethod]
    void TestMethod1()
    {
        MockSomeClass mock;
        int expected = 10;
        ON_CALL(mock, SomeFunction()).WillByDefault(Return(expected));
        AnotherClass realClass;
        int actual = realClass.AnotherFunction(mock);           
        Assert::AreEqual(expected, actual);
    };

I am using visual studio 2008 and gmock 1.6.0. What is wrong I am doing. on realClass.AnotherFunction i want mocked output from mock.SomeFunction().

Upvotes: 1

Views: 381

Answers (1)

Kristofer
Kristofer

Reputation: 3269

The problem is that SomeClass::SomeFunction(...) isn't virtual, make it virtual and it will work.

Update:

There is one more fundamental error that causes it to fail, that is the method signature of

int AnotherFunction(SomeClass obj)

which creates a new SomeClass object instance which will in it's turn cause the normal SomeFunction to be called, you should instead pass a reference to the mocked class as argument.

int AnotherFunction(SomeClass* obj)

and invoke it using

int actual = realClass.AnotherFunction(&mock);

Upvotes: 3

Related Questions