How to set GMock EXPECT_CALL to invoke two different functions for a mocked function

udhai_coder picture udhai_coder · Nov 30, 2012 · Viewed 11.6k times · Source

How to invoke two different functions when a mocked function is called in the tested function in "Test suite"?

Details: A mocked function is called twice in a tested function. When it is called the first time, it should invoke one function (a local function in test suite) and when called the second time, it should invoke another function (another local function in test suite).

So, how to set EXPECT_Call with "Invoke" for the above requirement?

Answer

BЈовић picture BЈовић · Nov 30, 2012

You should use WillOnce.

Something like this (not tested) :

struct A
{
  MOCK_METHOD0( foo, void());
};


class A_Test : public ::testing::Test
{
  A a;

  void bar1(){}
  void bar2(){}
};

TEST_F( A_Test, test_1 )
{
  EXPECT_CALL( a, foo() )
     .WillOnce( Invoke( this, &A_Test::bar1 ) )
     .WillOnce( Invoke( this, &A_Test::bar2 ) );
}