首页 > 解决方案 > std::function is not derived from 'std::reference_wrapper<_Tp>'

问题描述

Trying to unit test private callback method of a class. Callback is registered using function which I can mock and then by using EXPECT_CALL and SaveArg I can capture callback function to std::function test member and call it for testing purposes. That works fine.

The problem starts when callback method itself takes std::function as a parameter.

Production code:

Private callback method I am trying to test:

void
MyClass::callbackMethod(const Callback callback)

Callback which is taken as parameter to callbackMethod:

typedef std::function< void(void) > Callback;

Public function in which callback is bound:

void
MyClass::initialize(const Callback callback)
{
      m_SomeClass->registerCallback(std::bind(&MyClass::callbackMethod, this, callback));
}

Test code:

Tets class memeber to which I am trying to save callback argument from a register function:

std::function< void(const Callback callback) > m_Callback;

What should happen here:

EXPECT_CALL(*m_SomeClassMock, registerCallback(_))
         .WillOnce(SaveArg< 0 >(&m_Callback));

Gives following error:

...
/usr/include/c++/6/functional:1999:2: note: candidate: template<class _Functor> std::function<_Res(_ArgTypes ...)>& std::function<_Res(_ArgTypes ...)>::operator=(std::reference_wrapper<_Functor>) [with _Functor = _Functor; _Res = void; _ArgTypes = {std::function<void(void)>}]
  operator=(reference_wrapper<_Functor> __f) noexcept
  ^~~~~~~~
/usr/include/c++/6/functional:1999:2: note:   template argument deduction/substitution failed:
In file included from .../ext-cppunit-google-mock-dev/5/workspace/usr/include/gmock/gmock.h:65:0,
                 from .../SomeClassMock.hpp:15,
                 from .../MyTest.cpp:16:
.../gmock/gmock-more-actions.h:172:12: note:   'std::function<void(void)>' is not derived from 'std::reference_wrapper<_Tp>'
   *pointer = ::testing::get<k>(args);
   ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~

Not sure what is causing this error by maybe the fact that in last line of error probably there should be:

std::function<void(std::function<void(void)>)>

is giving some clue?

标签: c++unit-testinggooglemockgmock

解决方案


推荐阅读