我是 gmock 的新手,我想了解使用 SaveArg 时会发生什么。
这是我在 gmock 文档中找到的内容:
SaveArg<N>(pointer)
: 将第 N 个(从 0 开始)参数保存到 *pointer。
这是否意味着:
使“指针”指向第 N 个参数,或者
将第 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/