9

The constructor of my class is

A( ...
   std::function<bool(const std::string&, const std::string&)> aCallBack, 
   ... );

I want to use EXPECT_CALL to test it. This callback is from another class B. I created a Mock like

class BMock : public B
{
    MOCK_METHOD2( aCallBack, bool(const std::string&, const std::string&) );
}

Then I tried

B *b = new B();
std::function<bool(const std::string&, const std::string&)> func = 
    std::bind(&B::aCallBack, b, std::PlaceHolders::_1, std::PlaceHolders::_2);

It still does not work. How can I get a function pointer of a gmock object?

Thanks!!

Quarra
  • 2,527
  • 1
  • 19
  • 27
zeejan
  • 265
  • 1
  • 4
  • 10

2 Answers2

29

If you want to use mock to keep track of calls and set return values, you can use MockFunction.

using testing::_;
using testing::MockFunction;
using testing::Return;

MockFunction<bool(const std::string&, const std::string&)> mockCallback;

EXPECT_CALL(mockCallback, Call(_, _)).WillOnce(Return(false)); // Or anything else you want to do

A( ...
   mockCallback.AsStdFunction()
   ...);

Md Enzam Hossain
  • 1,246
  • 1
  • 11
  • 12
  • 7
    This is golden. Been looking for this across multiple related stack overflow posts, and your answer was the first I found that mentioned MockFunction and provided a complete example. – junvar Sep 27 '19 at 19:59
  • I am not sure why this was never mentioned in the documentation. Am I missing something? – Abdelrahman Shoman May 07 '20 at 15:30
  • It's documented in Cookbook at least - https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#mock-stdfunction-mockfunction – Md Enzam Hossain Jul 21 '20 at 13:35
  • Unfortunately, all `MockFunction`s are identified as `Call` in error messages which is very unhelpful... – Rufus Mar 10 '21 at 06:44
-3

With unit testing you should only test your class A so your test should just check if any function passed to the constructor gets called. So you don't need a mock, instead just pass a lambda that just record with a boolean (or a counter).

bool gotCalled = false;
A a( [&gotCalled]( const std::string&, const std::string& ) { gotCalled = true; return true; } );
...
ASSERT_TRUE( gotCalled );
Paolo Vigori
  • 1,612
  • 1
  • 18
  • 32
  • Anyway, although it's fine passing a function to the constructor, architecturally it doesn't smell right if it's used as callback. Generally it would be better to pass it to the function that actually is using it. – Paolo Vigori Mar 02 '17 at 10:58
  • this answer has nothing to do with an actual solution to TS problem, for the actual answer please check Enzam's answer – Eugene K Jun 14 '20 at 21:08