繁体   English   中英

我如何在GoogleMock中检查作为无效指针传递的字符串参数

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

我想从第3方库中模拟免费的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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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