Mock Concrete Classes

1,611 views
Skip to first unread message

Kunal

unread,
Oct 10, 2009, 6:37:53 AM10/10/09
to Google C++ Mocking Framework
Hi,

Please giude with some examples on mocking real / concrete classes
instead of

interface, if possible using google mock. In this case, how to handle
mocking constructors

of the class.

Thanks & Regards,
Kunal

Keith Ray

unread,
Oct 11, 2009, 6:18:54 PM10/11/09
to Kunal, Google C++ Mocking Framework
Replace calls to constructors with to calls to factory objects with
factory methods that are virtual functions - mock virtual functions of
the factory object classes.

Mocking concrete classes with gmock is the same as mocking Astract
Base Classes - you need to mock virtual functions.

If the problem is that the code you want to test creates concrete
objects and uses them "by value" then you will need to refactor the
code to separate out responsibilities - creating an object and using
an object can be separated into separate methods. Production code
creates the real object and calls another method to us it. Test code
creates the mock object and passes that into that same "using" method
to be tested.

--
C. Keith Ray, IXP Coach, Industrial Logic, Inc.
http://industriallogic.com 866-540-8336 (toll free)
Groove with our Agile Greatest Hits: http://www.industriallogic.com/elearning/
http://agilesolutionspace.blogspot.com/

Kunal

unread,
Oct 12, 2009, 1:30:17 AM10/12/09
to Google C++ Mocking Framework
I have following issues with your proposed solution:

1. I need to write UT cases for legacy code, where no refactoring is
allowed.
2, Mocker must support all type of methods, virtual, non-virtual,
const, constructor.

Please suggest if something is possible with these two cases.

Keith Ray

unread,
Oct 12, 2009, 4:32:48 PM10/12/09
to Kunal, Google C++ Mocking Framework
Sorry, unit testing with mock objects generally requires that you
modify legacy code. If you can't make any modifications to it (ala
Michael Feather's "Working Effectively WIth Legacy Code") then you are
limited to system and sub-system tests.

You might be better off asking why someone is asking you to attempt
the nearly impossible.

At the last resort you can use the precompiler to alter the sources
that you are trying to test.

#define ClassYouWantToMock YourMockClass
#include "CodeUnderTest.cpp"
#undef ClassYouWantToMock

class YourMockClass { ... };

// Your tests go here....

--

Reply all
Reply to author
Forward
0 new messages