Calling a method when expected method on mock was invoked

Martin picture Martin · Apr 27, 2011 · Viewed 13.3k times · Source

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

Answer

VladLosev picture VladLosev · Apr 28, 2011
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.