简体   繁体   中英

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

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*&)

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);
}

This helped: https://groups.google.com/forum/#!topic/googlemock/-zGadl0Qj1c

The solution is to write my own parameter matcher that performs the necessary cast:

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

And use it instead of StrEq

  EXPECT_CALL(m, foo(StrEqVoidPointer("ExpectedString"),2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM