Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set EXPECT_CALL to redirect the call to the original method

Tags:

gmock

I have a class with several methods that depend on each other. Lets say foo(), bar() and baz().

When I test bar() I need to mock the behavior of foo(), when I test baz() I need to mock the behavior of bar().

If I mock bar for baz I cannot use the same mock class to test bar with the mocked foo().

My question is can I set EXPECT_CALL to actually call the original behavior and how. This will eliminate the need to create several Mock classes.

like image 214
gsf Avatar asked Aug 28 '14 19:08

gsf


1 Answers

Answer can be found in gMock Cookbook.

In short, you need to write

class MockFoo : public Foo {
public:
  // Mocking a pure method.
  MOCK_METHOD(void, Pure, (int n), (override));
  // Mocking a concrete method.  Foo::Concrete() is shadowed.
  MOCK_METHOD(int, Concrete, (const char* str), (override));
};

and

ON_CALL(foo, Concrete).WillByDefault([&foo](const char* str) {
  return foo.Foo::Concrete(str);
});

or

EXPECT_CALL(foo, Concrete).WillOnce([&foo](const char* str) {
  return foo.Foo::Concrete(str);
});
like image 200
Haozhun Avatar answered Oct 02 '22 03:10

Haozhun