How can I check a string parameter in googlemock that is passed as void pointer

Lud*_*lze 2 c++ googlemock

I would like to mock free C functions from a 3rd-party library. I know googlemock recommends to wrap the functions as methods in an interface class.

Some C functions expect void* parameters, the interpretation of which depends on context. In one test case, a 0-terminated string is used for a void* parameter.

In the mock object, I would like to check the string's content, when it was transmitted as a void*. When I try to use StrEq to check the string content, then it does not work:

error: no matching function for call to std::__cxx11::basic_string<char>::basic_string(void*&)
Run Code Online (Sandbox Code Playgroud)

I do not want to change the data type in the wrapper from void* to char* to make this work, since the data passed through this parameter can also be something else. What can I do to check the data pointed to by a void* with googlemock's parameter matchers, preferably comparing for string equality?

The code. It would compile if you add some definition for function Foo and link against gmock_main.a, except for the above error.

#include <gmock/gmock.h>

// 3rd party library function, interpretation of arg depends on mode
extern "C" int Foo(void * arg, int mode);

// Interface class to 3rd party library functions
class cFunctionWrapper {
public:
  virtual int foo(void * arg, int mode) { Foo(arg,mode); }
  virtual ~cFunctionWrapper() {}
};

// Mock class to avoid actually calling 3rd party library during tests
class mockWrapper : public cFunctionWrapper {
public:
  MOCK_METHOD2(foo, int(void * arg, int mode));
};

using ::testing::StrEq;
TEST(CFunctionClient, CallsFoo) {
  mockWrapper m;
  EXPECT_CALL(m, foo(StrEq("ExpectedString"),2));
  char arg[] = "ExpectedString";
  m.foo(arg, 2);
}
Run Code Online (Sandbox Code Playgroud)

Lud*_*lze 6

这有帮助:https : //groups.google.com/forum/#!topic/ googlemock/ -zGadl0Qj1c

解决方案是编写我自己的参数匹配器来执行必要的转换:

MATCHER_P(StrEqVoidPointer, expected, "") {
  return std::string(static_cast<char*>(arg)) == expected;
}
Run Code Online (Sandbox Code Playgroud)

并使用它代替 StrEq

  EXPECT_CALL(m, foo(StrEqVoidPointer("ExpectedString"),2));
Run Code Online (Sandbox Code Playgroud)