Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use gmock to mock up a std::function?

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!!

like image 230
zeejan Avatar asked Mar 01 '17 00:03

zeejan


1 Answers

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()
   ...);

like image 73
Md Enzam Hossain Avatar answered Oct 19 '22 04:10

Md Enzam Hossain