C++ gmock - 将空指针传递给 SaveArg 时会发生什么

标签 c++ pointers googlemock nullptr

我是 gmock 的新手,我想了解使用 SaveArg 时会发生什么。

这是我在 gmock 文档中找到的内容:

SaveArg<N>(pointer) : 将第 N 个(从 0 开始)参数保存到 *pointer。

这是否意味着:

  1. 使“指针”指向第 N 个参数,或者

  2. 将第 N 个参数的值赋给“指针”指向的任何内容?

我在考虑以下情况:

class MockClass : public BaseClass {
 public:
    MOCK_METHOD1(somefunc,void(SomeType&));
};

然后在我的测试函数中:

SomeType val; //make this live throughout the test
SomeType* pval = nullptr;

MockClass mymock;
EXPECT_CALL(mymock, somefunc(_)).WillOnce(SaveArg<0>(pval));

//let's force a call
mymock.somefunc(val);

EXPECT_NE(nullptr, pval);

我的观点是:

如果 (1) 为真,那么会发生什么:pval = &val --> 测试将通过。

如果 (2) 为真,那么会发生什么:*pval = val --> 这将导致 pval 为空指针的段错误。

我的情况与上述情况类似,我将 nullptr 传递给 SaveArg 并且没有出现段错误,但测试也没有通过。

如果你们能帮助我,我将不胜感激。

谢谢

最佳答案

问题:

SaveArg(pointer) : Save the N-th (0-based) argument to *pointer.

does this mean:

make "pointer" point to the N-th argument, or assign the value of the N-th argument to whatever pointed to by "pointer" ?

编辑(VladLosev 更正)它本质上是第二个,将第 N 个参数的值复制到指针指向的任何内容。

因此,关于您观察到的行为:

I have a situation similar to the one above, where I pass a nullptr to SaveArg and do not get segmentation fault, but the test is not passed either.

这是由于 EXPECT_NE 的实现细节。这是来自 googletest FAQ 的一小段关于此事:

Due to some peculiarity of C++, it requires some non-trivial template meta programming tricks to support using NULL as an argument of the EXPECT_XX() and ASSERT_XX() macros. Therefore we only do it where it's most needed (otherwise we make the implementation of Google Test harder to maintain and more error-prone than necessary).

简短的回答,在使用 googletest 与 null 进行比较时,您应该使用 ASSERT_EQ 或 EXPECT_EQ 或 *_TRUE 的某些变体。有关详细信息,请点击常见问题解答条目上的链接。

关于C++ gmock - 将空指针传递给 SaveArg 时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46715522/

相关文章:

c - 将字符指针转换为交换函数的 void 指针的问题

c++ - 如何仅覆盖一个 EXPECT_CALL 的默认 ON_CALL 操作并稍后返回默认操作

c++ - 如何正确地使模拟方法调用原始虚方法

c++ - 使用C++中的模板从函数返回指针

c++ - FlatBuffers:不支持的 union vector 将 JSON 文件转换为二进制文件时出错

c++ - 通过指针成员传递类

c++ - 如何检查 std::unique_ptr<int[]> 中的元素?

c++ - 当boost线程被回收时,在其中创建的临时变量会从内存中删除吗?

c++ - Clock_gettime() 函数输出不正确的时间

c - 结构声明中的指针与局部变量