C 字符串永远不会在 gmock 中调用

C-string will never be called in gmock

本文关键字:gmock 调用 字符串 永远      更新时间:2023-10-16

我有一个C++函数要测试,在这个C++函数中,它将调用一个C函数。我想用Gmock来模拟这个C函数。C 函数的签名为:

int functionA(const char key[3],char value[6]);

int是返回码,输入key,输出value。我想模拟返回值并设置第二个参数。

我想测试C++函数是:

int functionB{
     ....
     int rcode = functionA(key, value);
     .......
}

我的"模拟"是:

#include<functionA.h>
#include <gmock/gmock.h>
class function_A_interface {
public:
   virtual int functionA(const char key[3],char value[6]) = 0;
};
class function_A_mock : public function_A_interface {
public:
   MOCK_METHOD2(functionA, int(const char[3], char[6]));
}

我的"mock.cc"是:

#include <function_A_mock.h>
extern function_A_mock MockObj;
int function_A(const char key[3],char value[6])
{
    return MockObj.functionA(key, value);
}

我的"test.t.cpp"是:

TEST(Test, tes){
function_A_mock MockObj;
 pa[3] = {0};
 pb[6] = {1};
 EXPECT_CALL(MockObj, functionA(pa, pb)).WillOnce(DoAll(SetArgPointee<1>(*set), Return(3)));
  functionB(parameter1, parameter2); // it will convert these two paramters to according input in functionA
}

但它向我展示了:

Unexpected mock function call - returning default value.
    Function call: functionA(ffbfc5b0 pointing to "abc      E", ffbfc570 pointing to "")
          Returns: 0
Google Mock tried the following 1 expectation, but it didn't match:
test.t.cpp:121: EXPECT_CALL(MockObj, functionA(pa, pb))...
  Expected arg #0: is equal to ffbfd380 pointing to "abc      E"
           Actual: ffbfc5b0 pointing to "abc      E"
  Expected arg #1: is equal to ffbfd340 pointing to ""
           Actual: ffbfc570 pointing to ""
         Expected: to be called once
           Actual: never called - unsatisfied and active

似乎我永远无法匹配我设置的参数,因此永远不会调用它。在我的情况下,如何模拟 C 字符串以进行匹配和设置参数目的?谢谢。

如果您不提供任何其他匹配器来模拟函数参数,则假定Eq()Eq()匹配器非常简单 - 它使用 operator == 将收到的参数与预期的参数进行比较。但是对于 C 样式字符串,此比较比较的是指针,而不是实际字符串。

您应该使用匹配器来比较StrEq

using ::testing::StrEq;
EXPECT_CALL(MockObj, functionA(StrEq(pa), StrEq(pb)))
       .WillOnce(DoAll(SetArgPointee<1>(*set), Return(3)));

但是,StrEq()会将内容作为以 null 结尾的字符串进行比较。如果要比较整个数组,请使用ElementsAreArray(array, count)

EXPECT_CALL(MockObj, functionA(ElementsAreArray(pa, 3), ElementsAreArray(pb, 6)))
       .WillOnce(DoAll(SetArgPointee<1>(*set), Return(3)));