gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:37:39 31 4
gpt4 key购买 nike

我有一个要测试的 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 字符串?谢谢。

最佳答案

如果您不提供任何其他匹配器来模拟函数参数,则假定为 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)));

关于c++ - 永远不会在 gmock 中调用 C 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56548791/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com