模拟一个以双指针作为参数的函数
mock a function which has double pointer as argument
模拟一个具有原始双指针的方法,例如下面 class Helper 有一个方法 int 运行(int** a)。我正在尝试使用 SetArgPointee 设置期望值,但它不起作用。给出编译器错误 Can not convert int** const to int*.
class Helper {
public:
MOCK_METHOD1(run, int(int ** a));
};
int** test = new int*[2];
test[0] = new int[1];
test[0][0] = 5;
test[1] = new int[1];
test[1][0] = 55;
int** test2 = new int*[2];
test2[0] = new int[1];
test2[0][0] = 10;
test2[1] = new int[1];
test2[1][0] = 110;
Helper helper;
EXPECT_CALL(helper, run(_))
.Times(1)
.WillOnce(DoAll(SetArgPointee<0>(test2), Return(99)));
int rc = helper.run(test);
我无法用 test2 替换测试双指针。想知道怎么做。
这不是一个完整的答案,但我会post它,因为它对于评论来说太长了。
首先,您可能应该解释一下您想要实现什么,因为通常没有理由设置被调用的模拟函数参数(至少,如果您不打算对修改后的 arg 做任何其他事情) .
SetArgPointee
只允许您将值设置为 a[0]
,因为这是您的指针指向的内存:
int** mockInput1 = new int*[2];
int** mockInput2 = new int*[2];
EXPECT_CALL(helper, run(_))
.Times(1)
// this will set value pointed by mockInput2[0] to mockInput1[0]
.WillOnce(DoAll(SetArgPointee<0>(mockInput1[0]), Return(99)));
helper.run(mockInput2);
但是,我几乎可以肯定这不是您要找的。请注意,gmock 允许您定义可以在您的呼叫匹配后调用的自定义操作:
auto action = [](int** a) {
int** test = new int*[2];
test[0] = new int[1];
test[0][0] = 5;
test[1] = new int[1];
test[1][0] = 55;
a[0] = test[0];
a[1] = test[1]; // or whatever
std::cout << "Executed custom action" << std::endl;
};
EXPECT_CALL(helper, run(_))
.Times(1)
.WillOnce(DoAll(Invoke(action), Return(99)));
helper.run(mockInput2);
在动作中你可以做任何你想做的事。不管怎样,试着解释一下你到底想达到什么目的。
另外,如果您没有适当删除内存,请注意内存泄漏的可能性。
模拟一个具有原始双指针的方法,例如下面 class Helper 有一个方法 int 运行(int** a)。我正在尝试使用 SetArgPointee 设置期望值,但它不起作用。给出编译器错误 Can not convert int** const to int*.
class Helper {
public:
MOCK_METHOD1(run, int(int ** a));
};
int** test = new int*[2];
test[0] = new int[1];
test[0][0] = 5;
test[1] = new int[1];
test[1][0] = 55;
int** test2 = new int*[2];
test2[0] = new int[1];
test2[0][0] = 10;
test2[1] = new int[1];
test2[1][0] = 110;
Helper helper;
EXPECT_CALL(helper, run(_))
.Times(1)
.WillOnce(DoAll(SetArgPointee<0>(test2), Return(99)));
int rc = helper.run(test);
我无法用 test2 替换测试双指针。想知道怎么做。
这不是一个完整的答案,但我会post它,因为它对于评论来说太长了。
首先,您可能应该解释一下您想要实现什么,因为通常没有理由设置被调用的模拟函数参数(至少,如果您不打算对修改后的 arg 做任何其他事情) .
SetArgPointee
只允许您将值设置为 a[0]
,因为这是您的指针指向的内存:
int** mockInput1 = new int*[2];
int** mockInput2 = new int*[2];
EXPECT_CALL(helper, run(_))
.Times(1)
// this will set value pointed by mockInput2[0] to mockInput1[0]
.WillOnce(DoAll(SetArgPointee<0>(mockInput1[0]), Return(99)));
helper.run(mockInput2);
但是,我几乎可以肯定这不是您要找的。请注意,gmock 允许您定义可以在您的呼叫匹配后调用的自定义操作:
auto action = [](int** a) {
int** test = new int*[2];
test[0] = new int[1];
test[0][0] = 5;
test[1] = new int[1];
test[1][0] = 55;
a[0] = test[0];
a[1] = test[1]; // or whatever
std::cout << "Executed custom action" << std::endl;
};
EXPECT_CALL(helper, run(_))
.Times(1)
.WillOnce(DoAll(Invoke(action), Return(99)));
helper.run(mockInput2);
在动作中你可以做任何你想做的事。不管怎样,试着解释一下你到底想达到什么目的。
另外,如果您没有适当删除内存,请注意内存泄漏的可能性。