Google mock ByRef method

对着背影说爱祢 提交于 2019-12-01 02:59:27
πάντα ῥεῖ

Your question is hard to get! The samples from google mocks 'cook book' are so as well.

Do you want to reuse the implementation for Foo::myMethod() with you mock class, or do you just want to mock the side effects (return value and changed by ref parameters) for specific call situations?

A mock class is usually meant to replace / simulate your Foo class, not to inherit it directly or it's behavior. Don't know if the way you define this 'default' behavior for a pure method will work, but doubt that. You might simply omit the = 0 then. The better approach would be to separate out a real interface declaration like:

struct IFoo
{
    virtual int myMethod(bool &my_boolean) = 0;
    virtual ~IFoo() {}
};

class Foo : public IFoo
{
    // ...
};

class MockFoo : public IFoo
{
   MOCK_METHOD1(myMethod,int(bool &my_boolean));
};

If you have the latter case, you should get off with testing::Return(value) and testing::SetArgReferee<N>(value) (found that in the very useful 'Cheat Sheet').

Your expectation call should look like this then:

MockFoo foo;

// Expect call to myMethod() return -1 and set the by ref argument to true
EXPECT_CALL(foo, myMethod(_))
  .WillOnce(DoAll(SetArgReferee<0>(true),Return(-1)));

// Expect call to myMethod() return 0 and set the by ref argument to false
EXPECT_CALL(foo, myMethod(_))
  .WillOnce(DoAll(SetArgReferee<0>(false),Return(0)));

If you really want to reuse your original classes logic for myMethod() have a look at 'Delegating calls to a parent class', resp. 'Delegating Calls to a Real Object'

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!