Need a suggestion in testing C style callback function with gooogletest gmock.
It's easy to test a callback defined with std::function
.
These 2 topics helped a lot:
But unfortunately my environment can't use std::
namespace (Arduino AVR platform).
So if I change from std::function
to C style callback like:
typedef void (*CallbackFunction)(void *);
then it doesn't compile, and I get the following error:
error: cannot convert ‘std::function<void(void*)>’ to ‘Foo::CallbackFunction’ {aka ‘void (*)(void*)’}
Any help appreciated.
Please see the code below:
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using ::testing::_;
using ::testing::MockFunction;
using ::testing::Return;
class Foo
{
public:
using CallbackFunction = std::function<void(void *)>; //* works just fine
// typedef void (*CallbackFunction)(void *); //! doesn't work
void SetCallback(CallbackFunction callback)
{
_callback = callback;
}
void InvokeCallback()
{
_callback(nullptr);
}
private:
CallbackFunction _callback;
};
class FooTest : public testing::Test
{
public:
using CallbackFunctionMock = testing::MockFunction<void(void *)>;
CallbackFunctionMock callbackFunctionMock;
};
TEST_F(FooTest, simple)
{
EXPECT_CALL(callbackFunctionMock, Call(_)).Times(1);
Foo foo;
foo.SetCallback(callbackFunctionMock.AsStdFunction());
foo.InvokeCallback();
}