簡體   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