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

时间:2019-06-11 17:18:01

标签: c++ testing c-strings gmock

我有一个要测试的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);
     .......
}

我的“ mock.h”是:

#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字符串?谢谢。

1 个答案:

答案 0 :(得分:0)

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

您应该使用StrEq匹配器进行比较:

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

但是,StrEq()会将事物比较为以零结尾的字符串。如果要比较整个数组,请使用ElementsAreArray(array, count)

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