Question

I am new to Google Mock and was trying my hand with this code, I also checked this link.

Actual function call count doesn't match EXPECT_CALL(*mock, display())

but was not able to get proper input.

Base.cc

class Base
{
    int val;
    string msg;
    public:
    Base():val(0), msg("world"){}
    virtual ~Base(){}
    virtual void set(int x, string msg)
    {
            this->val = val;
            this->msg = msg;
    }
    virtual void get()
    {
            cout << "val    :" << this->val << endl;
            cout << "msg    :" << this->msg << endl;
    }
};
class MockBase : public Base
{
    public:
    MOCK_METHOD0(get, void());
    MOCK_METHOD2(set, void(int val, string msg));
};

Base_unittest.cc

int main(int argc, char * argv[])
{
    std::cout << "in main" << endl;
    ::testing::InitGoogleTest(&argc,argv);
    return RUN_ALL_TESTS();
}
TEST(Base, case1)
{
    MockBase obj;
    EXPECT_CALL(obj, get()).WillOnce(::testing::Return());
}
TEST(Base, case2)
{
    MockBase obj;
    EXPECT_CALL(obj, set(2,"hello")).WillOnce(::testing::Return());
}

I am getting error:

Actual function call count doesn't match EXPECT_CALL(obj, get())...

Actual function call count doesn't match EXPECT_CALL(obj, set(2,"hello"))...

So please help and if any tutorials for newbies please refer.

Was it helpful?

Solution

Your expectation is saying that when obj is destroyed you expect that function to have been called one time. You are getting failures because the function is not actually being called.

TEST(Base, case1)
{
    MockBase obj;
    EXPECT_CALL(obj, get()).WillOnce(::testing::Return());
    obj.get();
}

Would cause this case to pass. Obviously this isn't very useful, normally you would inject the mock into the object under test. Also note that the action in this case is unnecessary, the following will work.

TEST(Base, case1)
{
    MockBase obj;
    EXPECT_CALL(obj, get());
    obj.get();
} 

Google has some good references:

https://github.com/google/googletest/blob/master/googlemock/docs/for_dummies.md

https://github.com/google/googletest/blob/master/googlemock/docs/cheat_sheet.md

https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top