Mocking a method which returns a string iterator

822 views
Skip to first unread message

leefw

unread,
Nov 26, 2010, 3:00:24 AM11/26/10
to Google C++ Mocking Framework
Hi

I am new to GMock and am wondering what the correct approach is for
mocking a method with the following definition:

vector<string>::iterator MyClass::GetMyIterator();

I would like to do something similar to :

EXPECT_CALL(myMockedClass, GetMyIterator())
.Times(3)
.WillOnce(Return("string vector value 1"))
.WillOnce(Return("string vector value 2"))
.WillOnce(Return("string vector value 3"));

Can this be done at all?

Regards
Lee Francis wilhelmsen

Piotr Gorak

unread,
Nov 26, 2010, 6:01:42 AM11/26/10
to Google C++ Mocking Framework
I think what you want to do is:

- create a vector of strings in your test code
- obtain this vector's iterator
- return this iterator from your mocked method (once)

Piotr

leefw

unread,
Nov 26, 2010, 9:05:37 AM11/26/10
to Google C++ Mocking Framework
Thanks! However, I'm not really that familiar with GMock. Do you think
you can provide a very simple example?

I am guessing something like this (this probably doesn't compile). How
do you write this point 3 of your proposal?

vector<string> v;
v.push_back("1");
v.push_back("2");
v.push_back("3");
v::iterator iter;
iter.front();

class MyMock ...
MOCK_METHOD0(GetMyIterator, vector<string>::iterator());
...

EXPECT_CALL(myMockedClass, GetMyIterator())
.WillOnce(Return(iter));


How do you iterate over the values of the test vector?

I hope I'm making sence here... ;->

regards
Lee Francis

Keith Ray

unread,
Nov 26, 2010, 8:12:33 PM11/26/10
to leefw, Google C++ Mocking Framework
you're close

class MyMock : public YourClass
{
public:
  MOCK_METHOD0(GetMyIterator, vector<string>::iterator());
etc...
};

TEST(YourTests, UsingMock)
{
vector<string> v;
v.push_back("1");
v.push_back("2");
v.push_back("3");
v::iterator iter;
iter.front();
MyMock myMockedClass;
EXPECT_CALL(myMockedClass, GetMyIterator())
   .WillOnce(Return(iter));

// code under test that uses myMockedClass
}
--
--
C. Keith Ray
 Web: http://industriallogic.com
 Twitter: @CKeithRay, @IndustrialLogic

Amplify Your Agility
Coaching | Training | Assessment | eLearning
Reply all
Reply to author
Forward
0 new messages