I'm new to gmock and I'd like to understand the what happens when using SaveArg.

Here's what I found in gmock docu:

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

does this mean:

  1. make "pointer" point to the N-th argument, or

  2. assign the value of the N-th argument to whatever pointed to by "pointer" ?

I'm thinking of the following situation:

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

then in my test function:

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);

My point is:

if (1) is true, then what happens is: pval = &val --> the test will go through.

if (2) is true, then what happens is: *pval = val --> this will cause segmentation fault for pval is null pointer.

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.

Would really appreciate if you guys could help me out.

Thanks

1 Answers 11

Question:

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" ?

Edit (correction by VladLosev) It's essentially the second, copy value of the N-th argument to whatever pointed by pointer.

So, regarding your observed behavior:

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.

This is due to implementation details of EXPECT_NE. Here's a short snippet from the googletest FAQ on the matter:

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).

Short answer, when comparing to null with googletest, you should use ASSERT_EQ or EXPECT_EQ or some variation of *_TRUE. For more details, follow the link on the FAQ entry.

1 upvote
  flag
SaveArg is (2). The implementation code makes that abundantly clear. – VladLosev
upvote
  flag
I wrote another piece of test code and can confirm that (2) is the actual behaviour. Thanks a lot for helping me out @iheanyi VladLosev . – astro_son

Not the answer you're looking for? Browse other questions tagged or ask your own question.