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

北慕城南 提交于 2020-05-16 03:25:07

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/42521088/how-to-use-gmock-to-mock-up-a-stdfunction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!