【问题标题】:How can I check a string parameter in googlemock that is passed as void pointer如何检查 googlemock 中作为 void 指针传递的字符串参数
【发布时间】:2017-04-05 16:15:27
【问题描述】:

我想模拟来自第 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);
}

【问题讨论】:

    标签: c++ googlemock


    【解决方案1】:

    这有帮助: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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-13
      • 2023-04-08
      • 2021-04-08
      • 2013-01-04
      • 2021-02-25
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多