1.`NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`)is**not**supported.
1.Duringtheconstructorordestructorof`MockFoo`, the mock object is _not_ nice or strict. This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual. In other words, to the base class's constructor or destructor, `this`objectbehaveslikeaninstanceofthebaseclass,notthederivedclass.Thisruleisrequiredforsafety.Otherwiseabaseconstructormayusemembersofaderivedclassbeforetheyareinitialized,orabasedestructormayusemembersofaderivedclassaftertheyhavebeendestroyed.)
*Differentprojectsmayneedtouse`Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`,andtheywillnotbethesamecode.
*Ifenoughprojectswanttousethesameinterface,theycanalwaysshareit,justliketheyhavebeensharing`Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib`sub-directory)andletmanyprojectsuseit.
*Thegeneraltechniquediscussedhereworksforoverloadedmethods,butyou'llneedtotellthecompilerwhichversionyoumean.Todisambiguateamockfunction(theoneyouspecifyinsidetheparenthesesof`ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. For instance, if class `Foo` has methods `char DoThis(int n)` and `bool DoThis(double x) const`, and you want to invoke the latter, you need to write `Invoke(&fake_, static_cast<bool (FakeFoo::*)(double) const>(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` (The strange-looking thing inside the angled brackets of `static_cast` is the type of a function pointer to the second `DoThis()`method.).
usinga`Matcher<long>` to match an `int`-afterall,wecanfirst
convertthe`int` argument to a `long`beforegivingittothe
matcher.
Tosupportthisneed,GoogleMockgivesyouthe
`SafeMatcherCast<T>(m)` function. It casts a matcher `m`totype
`Matcher<T>`. To ensure safety, Google Mock checks that (let `U`bethe
type`m`accepts):
1.Type`T` can be implicitly cast to type `U`;
1.Whenboth`T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`);and
1.When`U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U`value).
*`ElementsAre*()` can be used to match _any_ container that implements the STL iterator pattern (i.e. it has a `const_iterator` type and supports `begin()/end()`),notjusttheonesdefinedinSTL.Itwillevenworkwithcontainertypesyettobewritten-aslongastheyfollowstheabovepattern.
Therearebasicallytwoconstructsfordefiningthebehaviorofamockobject:`ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when a mock method is called, but _doesn't imply any expectation on the method being called._ `EXPECT_CALL`notonlydefinesthebehavior,butalsosetsanexpectationthat_themethodwillbecalledwiththegivenarguments,forthegivennumberoftimes_(and_inthegivenorder_whenyouspecifytheordertoo).
Since`EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every `EXPECT_CALL`addsaconstraintonthebehaviorofthecodeundertest.Havingmoreconstraintsthannecessaryis_baaad_-evenworsethannothavingenoughconstraints.
Souse`ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend to verify that the call is made. For example, you may have a bunch of `ON_CALL`s in your test fixture to set the common mock behavior shared by all tests in the same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s to verify different aspects of the code's behavior. Compared with the style where each `TEST` has many `EXPECT_CALL`s,thisleadstoteststhataremoreresilienttoimplementationalchanges(andthuslesslikelytorequiremaintenance)andmakestheintentofthetestsmoreobvious(sotheyareeasiertomaintainwhenyoudoneedtomaintainthem).
Ifyouarebotheredbythe"Uninteresting mock function call"messageprintedwhenamockmethodwithoutan`EXPECT_CALL` is called, you may use a `NiceMock` instead to suppress all such messages for the mock object, or suppress the message for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO NOT suppress it by blindly adding an `EXPECT_CALL(...)`,oryou'llhaveatestthat'sapaintomaintain.
Acall`x.Y(...)` is **uninteresting** if there's _not even a single_ `EXPECT_CALL(x, Y(...))` set. In other words, the test isn't interested in the `x.Y()`methodatall,asevidentinthatthetestdoesn'tcaretosayanythingaboutit.
Acall`x.Y(...)` is **unexpected** if there are some `EXPECT_CALL(x, Y(...))s` set, but none of them matches the call. Put another way, the test is interested in the `x.Y()` method (therefore it _explicitly_ sets some `EXPECT_CALL`toverifyhowit'scalled);however,theverificationfailsasthetestdoesn'texpectthisparticularcalltohappen.
Thesole`EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have `"google.com"` as the argument. If `GetDomainOwner("yahoo.com")`iscalled,itwillbeanunexpectedcall,andthusanerror.Havinganicemockdoesn'tchangetheseverityofanunexpectedcall.
SohowdowetellGoogleMockthat`GetDomainOwner()` can be called with some other arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`:
```
EXPECT_CALL(mock_registry,GetDomainOwner(_))
.Times(AnyNumber());// catches all other calls to this method.
Rememberthat`_` is the wildcard matcher that matches anything. With this, if `GetDomainOwner("google.com")` is called, it will do what the second `EXPECT_CALL` says; if it is called with a different argument, it will do what the first `EXPECT_CALL`says.
Notethattheorderofthetwo`EXPECT_CALLs` is important, as a newer `EXPECT_CALL`takesprecedenceoveranolderone.
Formoreonuninterestingcalls,nicemocks,andstrictmocks,read["The Nice, the Strict, and the Naggy"](https://code.google.com/p/googlemock/wiki/CookBook#The_Nice,_the_Strict,_and_the_Naggy).
*Thetypesoftheselectedargumentsdo_not_havetomatchthesignatureoftheinneractionexactly.Itworksaslongastheycanbeimplicitlyconvertedtothecorrespondingargumentsoftheinneraction.Forexample,ifthe4-thargumentofthemockfunctionisan`int` and `my_action` takes a `double`, `WithArg<4>(my_action)`willwork.
A`Buzz` object represents a snippet being posted. A class that implements the `Buzzer` interface is capable of creating and sharing `Buzz`. Methods in `Buzzer` may return a `unique_ptr<Buzz>` or take a `unique_ptr<Buzz>`. Now we need to mock `Buzzer`inourtests.
Notethatthere'snoneedtodefineordeclare`DoShareBuzz()` in a base class. You only need to define it as a `MOCK_METHOD`inthemockclass.
Nowthatwehavethemockclassdefined,wecanuseitintests.Inthefollowingcodeexamples,weassumethatwehavedefineda`MockBuzzer` object named `mock_buzzer_`:
```
MockBuzzermock_buzzer_;
```
Firstlet’sseehowwecansetexpectationsonthe`MakeBuzz()` method, which returns a `unique_ptr<Buzz>`.
Asusual,ifyousetanexpectationwithoutanaction(i.e.the`.WillOnce()` or `.WillRepeated()` clause), when that expectation fires, the default action for that method will be taken. Since `unique_ptr<>` has a default constructor that returns a null `unique_ptr`,that’swhatyou’llgetifyoudon’tspecifyanaction:
Ifyouarenothappywiththedefaultaction,youcantweakit.Dependingonwhatyouneed,youmayeithertweakthedefaultactionforaspecific(mockobject,mockmethod)combinationusing`ON_CALL()`, or you may tweak the default action for all mock methods that return a specific type. The usage of `ON_CALL()` is similar to `EXPECT_CALL()`, so we’ll skip it and just explain how to do the latter (tweaking the default action for a specific return type). You do this via the `DefaultValue<>::SetFactory()` and `DefaultValue<>::Clear()`API:
```
// Sets the default action for return type std::unique_ptr<Buzz> to
Quiztime!Whatdoyouthinkwillhappenifa`Return(ByMove(...))` action is performed more than once (e.g. you write `….WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time the action runs, the source value will be consumed (since it’s a move-only value), so the next time around, there’s no value to move from -- you’ll get a run-time error that `Return(ByMove(...))`canonlyberunonce.
Everytimethis`EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created and returned. You cannot do this with `Return(ByMove(...))`.
Nowthere’sonetopicwehaven’tcovered:howdoyousetexpectationson`ShareBuzz()`, which takes a move-only-typed parameter? The answer is you don’t. Instead, you set expectations on the `DoShareBuzz()` mock method (remember that we defined a `MOCK_METHOD` for `DoShareBuzz()`, not `ShareBuzz()`):
Someofyoumayhavespottedoneproblemwiththisapproach:the`DoShareBuzz()` mock method differs from the real `ShareBuzz()` method in that it cannot take ownership of the buzz parameter - `ShareBuzz()` will always delete buzz after `DoShareBuzz()` returns. What if you need to save the buzz object somewhere for later use when `ShareBuzz()`iscalled?Indeed,you'dbestuck.
Anotherproblemwiththe`DoShareBuzz()` we had is that it can surprise people reading or maintaining the test, as one would expect that `DoShareBuzz()` has (logically) the same contract as `ShareBuzz()`.
`--gmock_verbose=LEVEL` command-line flag, where `LEVEL`isastring
withthreepossiblevalues:
*`info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL`macros.
1.Thetypeofthevaluebeingmatched(`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`;andsoon.