How to mock overloaded operators

6,273 views
Skip to first unread message

kendrick

unread,
Feb 20, 2010, 7:42:40 PM2/20/10
to Google C++ Mocking Framework
Hello,

I am trying to use GMock on an embedded C++ project using QT. Some
of the classes in the code are using overloaded operators [ i.e.
myClass::myClass &operator=(const myClass& klass) {...} ]

How can I mock this action?

The obvious does not work:

MOCK_METHOD1(operator=,myClass&(const myClass&));

Is there a way to mock operator methods?

Thanks,

KPB

Seb Rose (Claysnow Limited)

unread,
Feb 21, 2010, 12:05:00 AM2/21/10
to Google C++ Mocking Framework, kendrick
KPB,

I had the same question, and here's the answer I got.

In your mock class you need to define the operator(s) and foward calls
to a mock method.

Example:

class IAm {
public:
virtual ~IAm() {}
virtual bool operator==(const IAm&) = 0;
};

class MockIAm : public IAm {
public:
MOCK_METHOD1(Equals, bool(const IAm&));
virtual bool operator==(const IAm& rhs) { return Equals(rhs); }
};

MockIAm can be instantiated. You should set expectations on Equals()
instead of operator==:

MockIAm x;
EXPECT_CALL(x, Equals(_));


See Comment #3 on issue 53 by zhanyong.wan: Can googlemock mock C++ operators
http://code.google.com/p/googlemock/issues/detail?id=53

Cheers
Seb

--
ACCU - http://www.accu.org/ - Professionalism in Programming

Reply all
Reply to author
Forward
0 new messages