SaveArg used for multiple calls to the same function

5,838 views
Skip to first unread message

Patrick

unread,
Apr 11, 2011, 10:34:13 AM4/11/11
to Google C++ Mocking Framework, christia...@iathh.de, joachim....@iathh.de, patric...@iathh.de
I am using gmock v1.5 under linux. I created the following mocked
class with a function run(dataStruct*).

class MockQFClient : public QFClient {
public:
MOCK_METHOD1(run, void(dataStruct *data));
}

When run is called once and I use SaveArg one time to save a pointer
to data, the pointer has a valid address and the data contained within
in is valid.

dataStruct *data;
EXPECT_CALL(*mockClient, run(_))
.Times(1)
.WillOnce(testing::SaveArg<0>(&data));

When I use SaveArg two times because run() is called twice, the
pointer after the 2nd call is invalid and I cannot access the data.

EXPECT_CALL(*mockClient, run(_))
.Times(2)
.WillRepeatedly(SaveArg<0>(&data));

Could someone please explain if I am using SaveArg correctly, and if
so, what is causing such a problem.

I upgraded to v1.6 and used SaveArgPointee instead of SaveArg and
everything functioned as it should. However, I would still like to
know what is wrong in the case that I use SaveArg.

dataStruct data;
EXPECT_CALL(*mockClient, run(_))
.Times(2)
.WillRepeatedly(SaveArgPointee<0>(&data));

Martin Svensson

unread,
Apr 12, 2011, 2:36:08 AM4/12/11
to Patrick, Google C++ Mocking Framework, christia...@iathh.de, joachim....@iathh.de, patric...@iathh.de
The times that work are just luck. Remember that your mock is called
much later than EXPECT_CALL. So your flow is this:

1. Allocate variable on stack
2. EXPECT_CALL
3. Variable is deallocated
4. Mock called. Write variable with SaveArg

You need to make sure that the variable stays alive until the mock call
and subsequent uses.
For example by making it static (ugly) or making it a member variable of
your mock subclass (good).

/Martin

Reply all
Reply to author
Forward
0 new messages