**GoogleC++MockingFramework**(or**GoogleMock**forshort)isalibrary(sometimeswealsocallita"framework"tomakeitsoundcool)forcreatingmockclassesandusingthem.ItdoestoC++what[jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java.
GoogleMockwasbuilttohelpC++programmers.Itwasinspiredby[jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you:
Youcancontrolwhethertheturtle'smovementwillleaveatraceusing`PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()`tellyouthecurrentpositionoftheturtle.
1.Inthe`public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n`isthenumberofthearguments;ifyoucountedwrong,shameonyou,andacompilererrorwilltellyouso.
`gmock_gen.py` tool in Google Mock's `scripts/generator/`directory(courtesyofthe[cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line
Whenyoudefineamockclass,youneedtodecidewheretoputitsdefinition.Somepeopleputitina`*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`,canyou?)
So,theruleofthumbis:ifyouneedtomock`Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo`tochange,andonlyteststhatdependonthechangedmethodsneedtobefixed.
Anotherwaytodoit:youcanintroduceathinlayer`FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo`does.
// The following line must be executed to initialize Google Mock
// (and Google Test) before running the tests.
::testing::InitGoogleMock(&argc,argv);
returnRUN_ALL_TESTS();
}
```
Asyoumighthaveguessed,thistestchecksthat`PenDown()` is called at least once. If the `painter`objectdidn'tcallthismethod,yourtestwillfailwithamessagelikethis:
Themacrohastwoarguments:firstthemockobject,andthenthemethodanditsarguments.Notethatthetwoareseparatedbyacomma(`,`), not a period (`.`).(Whyusingacomma?Theansweristhatitwasnecessaryfortechnicalreasons.)
// Expects the turtle to move forward by 100 units.
EXPECT_CALL(turtle,Forward(100));
```
Sometimesyoumaynotwanttobetoospecific(Rememberthattalkabouttestsbeingtoorigid?Overspecificationleadstobrittletestsandobscurestheintentoftests.Thereforeweencourageyoutospecifyonlywhat'snecessary-nomore,noless.).Ifyoucaretocheckthat`Forward()` will be called but aren't interested in its actual argument, write `_`astheargument,whichmeans"anything goes":
```
using::testing::_;
...
// Expects the turtle to move forward.
EXPECT_CALL(turtle,Forward(_));
```
`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()`whereverafunctionargumentisexpected.
Thefirstclausewecanspecifyfollowingan`EXPECT_CALL()` is `Times()`.Wecallitsargumenta**cardinality**asittells_howmanytimes_thecallshouldoccur.Itallowsustorepeatanexpectationmanytimeswithoutactuallywritingitasmanytimes.Moreimportantly,acardinalitycanbe"fuzzy",justlikeamatchercanbe.Thisallowsausertoexpresstheintentofatestexactly.
First,ifthereturntypeofamockfunctionisabuilt-intypeorapointer,thefunctionhasa**defaultaction**(a`void` function will just return, a `bool` function will return `false`,andotherfunctionswillreturn0).Inaddition,inC++11andabove,amockfunctionwhosereturntypeisdefault-constructible(i.e.hasadefaultconstructor)hasadefaultactionofreturningadefault-constructedvalue.Ifyoudon'tsayanything,thisbehaviorwillbeused.
Second,ifamockfunctiondoesn'thaveadefaultaction,orthedefaultactiondoesn'tsuityou,youcanspecifytheactiontobetakeneachtimetheexpectationmatchesusingaseriesof`WillOnce()` clauses followed by an optional `WillRepeatedly()`.Forexample,
```
using::testing::Return;
...
EXPECT_CALL(turtle,GetX())
.WillOnce(Return(100))
.WillOnce(Return(200))
.WillOnce(Return(300));
```
Thissaysthat`turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`),andwillreturn100,200,and300respectively.
```
using::testing::Return;
...
EXPECT_CALL(turtle,GetY())
.WillOnce(Return(100))
.WillOnce(Return(200))
.WillRepeatedly(Return(300));
```
saysthat`turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`),willreturn100thefirsttime,200thesecondtime,and300fromthethirdtimeon.
Ofcourse,ifyouexplicitlywritea`Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.).
Whatcanwedoinside`WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`,orinvokeapre-definedfunction,among[others](CheatSheet.md#actions).
Insteadofreturning100,101,102,...,consecutively,thismockfunctionwillalwaysreturn100as`n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()`isexecuted,andwillreturnthesamepointereverytime.Ifyouwantthesideeffecttohappeneverytime,youneedtodefineacustomaction,whichwe'llteachinthe[CookBook](CookBook.md).
Obviously`turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int`functions.
If`Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`,thenitwouldbeOK,asnow#1willbethematchingexpectation.
Ifyouthinkitsaysthat`turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()`statementwillmatch,andwillimmediatelyleadtoan"upper bound exceeded"error-thispieceofcodeisnotveryuseful!
Congratulations!You'velearnedenoughaboutGoogleMocktostartusingit.Now,youmightwanttojointhe[googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned.