如何检查谷歌模拟中作为空指针传递的字符串参数

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

本文关键字:空指针 参数 字符串 何检查 检查 模拟 谷歌      更新时间:2023-10-16

我想模拟来自第三方库的免费 C 函数。我知道googlemock建议将这些函数包装为接口类中的方法。

一些 C 函数需要 void* 参数,其解释取决于上下文。在一个测试用例中,以 0 结尾的字符串用于 void* 参数。

在模拟对象中,我想检查字符串的内容,当它作为 void* 传输时。当我尝试使用 StrEq 检查字符串内容时,它不起作用:

error: no matching function for call to std::__cxx11::basic_string<char>::basic_string(void*&)

我不想将包装器中的数据类型从 void* 更改为 char* 来执行此操作,因为通过此参数传递的数据也可以是其他东西。我该怎么做才能使用 googlemock 的参数匹配器检查 void* 指向的数据,最好是比较字符串相等性?

代码。如果您为函数 Foo 添加一些定义并针对 gmock_main.a 的链接,它将编译,除了上述错误。

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

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

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

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

并使用它代替 StrEq

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