Reputation: 1897
Using c++17 and gmock, I am mocking a class and would like to redirect calls to one of its member functions to a lambda. Is this possible?
He're a minimal example:
#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);
}));
}
I am getting the following error when compiling:
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)>&
Upvotes: 1
Views: 4653
Reputation: 73196
The error messages of gmock can be somewhat cryptic, and it doesn't help when you are working with types that are typedefs to fundamental types; in this case uint8_t
.
If we look closer at the error message:
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)'
it's actually providing some hints:
OnCallSpec
of unsigned char(unsigned char)
,WillByDefault
) callable.The former, when looking at your program and manually translating in the fixed-width typedefs, actually tell us:
OnCallSpec
of uint8_t(uint8_t)
,which makes it more apparent that something is wrong with the type of the default callable, namely the lambda.
In this particular case, the return type of the lambda is (implicitly) void
, thus the mismatch of (disregarding CV-qualifiers) void(uint8_t)
with the "on call spec" of uint8_t(uint8_t)
.
Upvotes: 4