Calling a method when expected method on mock was invoked

て烟熏妆下的殇ゞ 提交于 2019-12-07 12:52:04

问题


I have the following scenario:

class InterfaceA;
class InterfaceB;
class InterfaceC;


class InterfaceA
{
  virtual void foo(InterfaceC&) = 0;
};

class InterfaceB
{
  virtual void bar() = 0;
};

class InterfaceC
{
  virtual void bla() = 0;
};

// MOCKs

class MockA : public InterfaceA
{
  public:
    MOCK_METHOD0(foo, void(InterfaceC&));
};

class MockB : public InterfaceB
{
  public:
    MOCK_METHOD0(bar, void());
};


class ImplC : public InterfaceC
{
  public:
    ImplC(InterfaceA& a, Interface& b) : m_a(a), m_b(b) {}

    void doSomething() {
      m_a.foo(*this);
    }

    virtual void bla()
    {
      m_b.bar();
    }
};

MockA mockA;
MockB mockB;

EXPECT_CALL(mockA, foo());

ImplC impl(mockA, mockB);

impl.doSomething(); // will call foo on mockA

In case doSomething is invoked, foo will be called on MockA. How can I trigger an invocation of the method bla, in case foo will be invoked? Is it somehow possible to create an expectation like:

EXPECT_CALL(mockA, foo()).WillOnce(Invoke(impl.bla()));

?

I hope the answer is clear and the example too.

Thanks in advance. Mart


回答1:


EXPECT_CALL(mockA, foo()).WillOnce(InvokeWithoutArgs(&impl, &ImplC::bla));

Should work. If you have to pass more complex parameters, use boost::bind (notice the different order of the class instance and method in the parameter list):

EXPECT_CALL(mockA, foo())
    .WillOnce(Invoke(boost::bind(&ImplC::bla, &impl, other_params)));

And if foo() is given some parameters that should be passed into bla(), use WithArgs:

EXPECT_CALL(mockA, foo(Lt(1), _))
    .WillOnce(WithArgs<0>(Invoke(&impl, &ImplC::bla)));

Also take a look at the Google Mock Cheat Sheet wiki page - it provides more information about function- and method calling actions.



来源:https://stackoverflow.com/questions/5807302/calling-a-method-when-expected-method-on-mock-was-invoked

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