使用c++17和gmock,我正在模拟一个类,并希望将对其中一个成员函数的调用重定向到一个lambda。这可能吗?
他是一个最小的例子。
#include <gmock/gmock.h>
using ::testing::_;
using ::testing::Invoke;
using ::testing::Return;
class Foo
{
public:
virtual uint8_t MyCall(const uint8_t in) const
{
return in;
}
};
class MockFoo : public Foo
{
public:
MOCK_METHOD(uint8_t, MyCall, (const uint8_t), (const, override));
};
TEST(MyTest, MyTestCase)
{
MockFoo mock_foo;
ON_CALL(mock_foo, MyCall(_)).WillByDefault(Invoke([](const uint8_t to) {
static_cast<void>(to);
}));
}
我在编译的时候得到了以下的错误信息:
demo.cpp: In member function 'virtual void MyTest_MyTestCase_Test::TestBody()':
demo.cpp:82:7: error: no matching function for call to 'testing::internal::OnCallSpec<unsigned char(unsigned char)>::WillByDefault(std::decay<MyTest_MyTestCase_Test::TestBody()::<lambda(uint8_t)> >::type)'
}));
^
In file included from external/gtest/googlemock/include/gmock/gmock-function-mocker.h:42:0,
from external/gtest/googlemock/include/gmock/gmock.h:61,
from demo.cpp:2:
external/gtest/googlemock/include/gmock/gmock-spec-builders.h:323:15: note: candidate: testing::internal::OnCallSpec<F>& testing::internal::OnCallSpec<F>::WillByDefault(const testing::Action<F>&) [with F = unsigned char(unsigned char)]
OnCallSpec& WillByDefault(const Action<F>& action) {
^~~~~~~~~~~~~
external/gtest/googlemock/include/gmock/gmock-spec-builders.h:323:15: note: no known conversion for argument 1 from 'std::decay<MyTest_MyTestCase_Test::TestBody()::<lambda(uint8_t)> >::type {aka MyTest_MyTestCase_Test::TestBody()::<lambda(uint8_t)>}' to 'const testing::Action<unsigned char(unsigned char)>&
gmock的错误信息可能有些神秘,当你在处理基本类型的typedefs类型时,它没有任何帮助,在这种情况下 uint8_t
.
如果我们仔细看一下错误信息。
error: no matching function for call to
'testing::internal::OnCallSpec<unsigned char(unsigned char)> ::WillByDefault(std::decay<MyTest_MyTestCase_Test::TestBody() ::<lambda(uint8_t)> >::type)'
它实际上提供了一些提示。
OnCallSpec
的 unsigned char(unsigned char)
,WillByDefault
)可调用。前者,当看你的程序,并手动翻译进固定宽度的类型定义时,其实告诉我们。
OnCallSpec
的 uint8_t(uint8_t)
,这使得默认的可调用类型,也就是lambda的类型有问题更加明显。
在这个特殊的情况下,lambda 的返回类型是(隐含地)。void
因此,(不考虑CV限定词)的不匹配性 void(uint8_t)
与 "待命规格 "为 uint8_t(uint8_t)
.