Index: ext/googletest/googlemock/docs/CookBook.md =================================================================== diff -u -N -r4a481bbe77043e0bda2435c6d62a02700b3e46c5 -r2e4eacb299f21d06196fe13140b4b0d095abdca9 --- ext/googletest/googlemock/docs/CookBook.md (.../CookBook.md) (revision 4a481bbe77043e0bda2435c6d62a02700b3e46c5) +++ ext/googletest/googlemock/docs/CookBook.md (.../CookBook.md) (revision 2e4eacb299f21d06196fe13140b4b0d095abdca9) @@ -18,8 +18,9 @@ `public:` section of the mock class, regardless of the method being mocked being `public`, `protected`, or `private` in the base class. This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function -from outside of the mock class. (Yes, C++ allows a subclass to change -the access level of a virtual function in the base class.) Example: +from outside of the mock class. (Yes, C++ allows a subclass to specify +a different access level than the base class on a virtual function.) +Example: ``` class Foo { @@ -147,7 +148,7 @@ real class. That's fine as long as the test doesn't need to call it. Next, you need a way to say that you want to use -`ConcretePacketStream` in production code, and use `MockPacketStream` +`ConcretePacketStream` in production code and to use `MockPacketStream` in tests. Since the functions are not virtual and the two classes are unrelated, you must specify your choice at _compile time_ (as opposed to run time). @@ -218,15 +219,15 @@ If you are concerned about the performance overhead incurred by virtual functions, and profiling confirms your concern, you can -combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md). +combine this with the recipe for [mocking non-virtual methods](#mocking-nonvirtual-methods). ## The Nice, the Strict, and the Naggy ## If a mock method has no `EXPECT_CALL` spec but is called, Google Mock will print a warning about the "uninteresting call". The rationale is: * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called. - * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning. + * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, they can add an `EXPECT_CALL()` to suppress the warning. However, sometimes you may want to suppress all "uninteresting call" warnings, while sometimes you may want the opposite, i.e. to treat all @@ -294,7 +295,7 @@ next guy, but sadly they are side effects of C++'s limitations): 1. `NiceMock` and `StrictMock` 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 >`) is **not** supported. - 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml). + 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](https://google.github.io/styleguide/cppguide.html). 1. During the constructor or destructor of `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` object behaves like an instance of the base class, not the derived class. This rule is required for safety. Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.) Finally, you should be **very cautious** about when to use naggy or strict mocks, as they tend to make tests more brittle and harder to maintain. When you refactor your code without changing its externally visible behavior, ideally you should't need to update any tests. If your code interacts with a naggy mock, however, you may start to get spammed with warnings as the result of your change. Worse, if your code interacts with a strict mock, your tests may start to fail and you'll be forced to fix them. Our general recommendation is to use nice mocks (not yet the default) most of the time, use naggy mocks (the current default) when developing or debugging tests, and use strict mocks only as the last resort. @@ -705,7 +706,7 @@ 1. When both `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). -The code won't compile if any of these conditions isn't met. +The code won't compile if any of these conditions aren't met. Here's one example: @@ -1029,9 +1030,10 @@ For example: -> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | +| Expression | Description | |:-----------------------------|:-----------------------------------| -> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | +| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | +| `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument and be declared as `const`. @@ -1229,7 +1231,7 @@ object will be deleted. Therefore, if you have some complex matcher that you want to use again -and again, there is no need to build it everytime. Just assign it to a +and again, there is no need to build it every time. Just assign it to a matcher variable and use that variable repeatedly! For example, ``` @@ -1401,7 +1403,7 @@ a DAG. We use the term "sequence" to mean a directed path in this DAG. Now, if we decompose the DAG into sequences, we just need to know which sequences each `EXPECT_CALL()` belongs to in order to be able to -reconstruct the orginal DAG. +reconstruct the original DAG. So, to specify the partial order on the expectations we need to do two things: first to define some `Sequence` objects, and then for each @@ -1680,7 +1682,7 @@ ``` using ::testing::_; -using ::testing::SeArrayArgument; +using ::testing::SetArrayArgument; class MockRolodex : public Rolodex { public: @@ -1919,9 +1921,9 @@ // second argument DoThis() receives. ``` -Arghh, you need to refer to a mock function argument but C++ has no -lambda (yet), so you have to define your own action. :-( Or do you -really? +Arghh, you need to refer to a mock function argument but your version +of C++ has no lambdas, so you have to define your own action. :-( +Or do you really? Well, Google Mock has an action to solve _exactly_ this problem: @@ -2180,7 +2182,7 @@ deleted. If you have some complex action that you want to use again and again, -you may not have to build it from scratch everytime. If the action +you may not have to build it from scratch every time. If the action doesn't have an internal state (i.e. if it always does the same thing no matter how many times it has been called), you can assign it to an action variable and use that variable repeatedly. For example: @@ -2227,110 +2229,85 @@ ## Mocking Methods That Use Move-Only Types ## -C++11 introduced move-only types. A move-only-typed value can be moved from one object to another, but cannot be copied. `std::unique_ptr` is probably the most commonly used move-only type. +C++11 introduced *move-only types*. A move-only-typed value can be moved from +one object to another, but cannot be copied. `std::unique_ptr` is +probably the most commonly used move-only type. -Mocking a method that takes and/or returns move-only types presents some challenges, but nothing insurmountable. This recipe shows you how you can do it. +Mocking a method that takes and/or returns move-only types presents some +challenges, but nothing insurmountable. This recipe shows you how you can do it. +Note that the support for move-only method arguments was only introduced to +gMock in April 2017; in older code, you may find more complex +[workarounds](#LegacyMoveOnly) for lack of this feature. -Let’s say we are working on a fictional project that lets one post and share snippets called “buzzes”. Your code uses these types: +Let’s say we are working on a fictional project that lets one post and share +snippets called “buzzes”. Your code uses these types: -``` +```cpp enum class AccessLevel { kInternal, kPublic }; class Buzz { public: - explicit Buzz(AccessLevel access) { … } + explicit Buzz(AccessLevel access) { ... } ... }; class Buzzer { public: virtual ~Buzzer() {} - virtual std::unique_ptr MakeBuzz(const std::string& text) = 0; - virtual bool ShareBuzz(std::unique_ptr buzz, Time timestamp) = 0; + virtual std::unique_ptr MakeBuzz(StringPiece text) = 0; + virtual bool ShareBuzz(std::unique_ptr buzz, int64_t timestamp) = 0; ... }; ``` -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` or take a `unique_ptr`. Now we need to mock `Buzzer` in our tests. +A `Buzz` object represents a snippet being posted. A class that implements the +`Buzzer` interface is capable of creating and sharing `Buzz`es. Methods in +`Buzzer` may return a `unique_ptr` or take a +`unique_ptr`. Now we need to mock `Buzzer` in our tests. -To mock a method that returns a move-only type, you just use the familiar `MOCK_METHOD` syntax as usual: +To mock a method that accepts or returns move-only types, you just use the +familiar `MOCK_METHOD` syntax as usual: -``` +```cpp class MockBuzzer : public Buzzer { public: - MOCK_METHOD1(MakeBuzz, std::unique_ptr(const std::string& text)); - … + MOCK_METHOD1(MakeBuzz, std::unique_ptr(StringPiece text)); + MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr buzz, int64_t timestamp)); }; ``` -However, if you attempt to use the same `MOCK_METHOD` pattern to mock a method that takes a move-only parameter, you’ll get a compiler error currently: +Now that we have the mock class defined, we can use it in tests. In the +following code examples, we assume that we have defined a `MockBuzzer` object +named `mock_buzzer_`: -``` - // Does NOT compile! - MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr buzz, Time timestamp)); -``` - -While it’s highly desirable to make this syntax just work, it’s not trivial and the work hasn’t been done yet. Fortunately, there is a trick you can apply today to get something that works nearly as well as this. - -The trick, is to delegate the `ShareBuzz()` method to a mock method (let’s call it `DoShareBuzz()`) that does not take move-only parameters: - -``` -class MockBuzzer : public Buzzer { - public: - MOCK_METHOD1(MakeBuzz, std::unique_ptr(const std::string& text)); - MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp)); - bool ShareBuzz(std::unique_ptr buzz, Time timestamp) { - return DoShareBuzz(buzz.get(), timestamp); - } -}; -``` - -Note that there's no need to define or declare `DoShareBuzz()` in a base class. You only need to define it as a `MOCK_METHOD` in the mock class. - -Now that we have the mock class defined, we can use it in tests. In the following code examples, we assume that we have defined a `MockBuzzer` object named `mock_buzzer_`: - -``` +```cpp MockBuzzer mock_buzzer_; ``` -First let’s see how we can set expectations on the `MakeBuzz()` method, which returns a `unique_ptr`. +First let’s see how we can set expectations on the `MakeBuzz()` method, which +returns a `unique_ptr`. -As usual, if you set an expectation without an action (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’s what you’ll get if you don’t specify an action: +As usual, if you set an expectation without an action (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’s what you’ll get if you don’t specify an +action: -``` +```cpp // Use the default action. EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); // Triggers the previous EXPECT_CALL. EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello")); ``` -If you are not happy with the default action, you can tweak it. Depending on what you need, you may either tweak the default action for a specific (mock object, mock method) combination using `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: +If you are not happy with the default action, you can tweak it as usual; see +[Setting Default Actions](#OnCall). -``` - // Sets the default action for return type std::unique_ptr to - // creating a new Buzz every time. - DefaultValue>::SetFactory( - [] { return MakeUnique(AccessLevel::kInternal); }); +If you just need to return a pre-defined move-only value, you can use the +`Return(ByMove(...))` action: - // When this fires, the default action of MakeBuzz() will run, which - // will return a new Buzz object. - EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber()); - - auto buzz1 = mock_buzzer_.MakeBuzz("hello"); - auto buzz2 = mock_buzzer_.MakeBuzz("hello"); - EXPECT_NE(nullptr, buzz1); - EXPECT_NE(nullptr, buzz2); - EXPECT_NE(buzz1, buzz2); - - // Resets the default action for return type std::unique_ptr, - // to avoid interfere with other tests. - DefaultValue>::Clear(); -``` - -What if you want the method to do something other than the default action? If you just need to return a pre-defined move-only value, you can use the `Return(ByMove(...))` action: - -``` +```cpp // When this fires, the unique_ptr<> specified by ByMove(...) will // be returned. EXPECT_CALL(mock_buzzer_, MakeBuzz("world")) @@ -2341,82 +2318,88 @@ Note that `ByMove()` is essential here - if you drop it, the code won’t compile. -Quiz time! What do you think will happen if a `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(...))` can only be run once. +Quiz time! What do you think will happen if a `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(...))` can only be run once. -If you need your mock method to do more than just moving a pre-defined value, remember that you can always use `Invoke()` to call a lambda or a callable object, which can do pretty much anything you want: +If you need your mock method to do more than just moving a pre-defined value, +remember that you can always use a lambda or a callable object, which can do +pretty much anything you want: -``` +```cpp EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) - .WillRepeatedly(Invoke([](const std::string& text) { - return std::make_unique(AccessLevel::kInternal); - })); + .WillRepeatedly([](StringPiece text) { + return MakeUnique(AccessLevel::kInternal); + }); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); ``` -Every time this `EXPECT_CALL` fires, a new `unique_ptr` will be created and returned. You cannot do this with `Return(ByMove(...))`. +Every time this `EXPECT_CALL` fires, a new `unique_ptr` will be +created and returned. You cannot do this with `Return(ByMove(...))`. -Now there’s one topic we haven’t covered: how do you set expectations on `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()`): +That covers returning move-only values; but how do we work with methods +accepting move-only arguments? The answer is that they work normally, although +some actions will not compile when any of method's arguments are move-only. You +can always use `Return`, or a [lambda or functor](#FunctionsAsActions): -``` - EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); +```cpp + using ::testing::Unused; - // When one calls ShareBuzz() on the MockBuzzer like this, the call is - // forwarded to DoShareBuzz(), which is mocked. Therefore this statement - // will trigger the above EXPECT_CALL. - mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), - ::base::Now()); + EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)) .WillOnce(Return(true)); + EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique(AccessLevel::kInternal)), + 0); + + EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)) .WillOnce( + [](std::unique_ptr buzz, Unused) { return buzz != nullptr; }); + EXPECT_FALSE(mock_buzzer_.ShareBuzz(nullptr, 0)); ``` -Some of you may have spotted one problem with this approach: 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()` is called? Indeed, you'd be stuck. +Many built-in actions (`WithArgs`, `WithoutArgs`,`DeleteArg`, `SaveArg`, ...) +could in principle support move-only arguments, but the support for this is not +implemented yet. If this is blocking you, please file a bug. -Another problem with the `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()`. +A few actions (e.g. `DoAll`) copy their arguments internally, so they can never +work with non-copyable objects; you'll have to use functors instead. -Fortunately, these problems can be fixed with a bit more code. Let's try to get it right this time: +##### Legacy workarounds for move-only types {#LegacyMoveOnly} -``` +Support for move-only function arguments was only introduced to gMock in April +2017. In older code, you may encounter the following workaround for the lack of +this feature (it is no longer necessary - we're including it just for +reference): + +```cpp class MockBuzzer : public Buzzer { public: - MockBuzzer() { - // Since DoShareBuzz(buzz, time) is supposed to take ownership of - // buzz, define a default behavior for DoShareBuzz(buzz, time) to - // delete buzz. - ON_CALL(*this, DoShareBuzz(_, _)) - .WillByDefault(Invoke([](Buzz* buzz, Time timestamp) { - delete buzz; - return true; - })); - } - - MOCK_METHOD1(MakeBuzz, std::unique_ptr(const std::string& text)); - - // Takes ownership of buzz. MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp)); - bool ShareBuzz(std::unique_ptr buzz, Time timestamp) { - return DoShareBuzz(buzz.release(), timestamp); + bool ShareBuzz(std::unique_ptr buzz, Time timestamp) override { + return DoShareBuzz(buzz.get(), timestamp); } }; ``` -Now, the mock `DoShareBuzz()` method is free to save the buzz argument for later use if this is what you want: +The trick is to delegate the `ShareBuzz()` method to a mock method (let’s call +it `DoShareBuzz()`) that does not take move-only parameters. Then, instead of +setting expectations on `ShareBuzz()`, you set them on the `DoShareBuzz()` mock +method: -``` - std::unique_ptr intercepted_buzz; - EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)) - .WillOnce(Invoke([&intercepted_buzz](Buzz* buzz, Time timestamp) { - // Save buzz in intercepted_buzz for analysis later. - intercepted_buzz.reset(buzz); - return false; - })); +```cpp + MockBuzzer mock_buzzer_; + EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); - mock_buzzer_.ShareBuzz(std::make_unique(AccessLevel::kInternal), - Now()); - EXPECT_NE(nullptr, intercepted_buzz); + // When one calls ShareBuzz() on the MockBuzzer like this, the call is + // forwarded to DoShareBuzz(), which is mocked. Therefore this statement + // will trigger the above EXPECT_CALL. + mock_buzzer_.ShareBuzz(MakeUnique(AccessLevel::kInternal), 0); ``` -Using the tricks covered in this recipe, you are now able to mock methods that take and/or return move-only types. Put your newly-acquired power to good use - when you design a new API, you can now feel comfortable using `unique_ptrs` as appropriate, without fearing that doing so will compromise your tests. + ## Making the Compilation Faster ## Believe it or not, the _vast majority_ of the time spent on compiling @@ -2482,12 +2465,12 @@ ## Forcing a Verification ## -When it's being destoyed, your friendly mock object will automatically +When it's being destroyed, your friendly mock object will automatically verify that all expectations on it have been satisfied, and will generate [Google Test](../../googletest/) failures if not. This is convenient as it leaves you with one less thing to worry about. That is, unless you are not sure if your mock object will -be destoyed. +be destroyed. How could it be that your mock object won't eventually be destroyed? Well, it might be created on the heap and owned by the code you are @@ -3347,6 +3330,7 @@ int DoSomething(bool flag, int* ptr); ``` we have: + | **Pre-defined Symbol** | **Is Bound To** | |:-----------------------|:----------------| | `arg0` | the value of `flag` | @@ -3508,14 +3492,15 @@ If you are writing a function that returns an `ACTION` object, you'll need to know its type. The type depends on the macro used to define the action and the parameter types. The rule is relatively simple: + | **Given Definition** | **Expression** | **Has Type** | |:---------------------|:---------------|:-------------| | `ACTION(Foo)` | `Foo()` | `FooAction` | | `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo()` | `FooAction` | | `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP` | | `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar(int_value)` | `FooActionP` | | `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2` | -| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz(bool_value, int_value)` | `FooActionP2` | +| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))`| `Baz(bool_value, int_value)` | `FooActionP2` | | ... | ... | ... | Note that we have to pick different suffixes (`Action`, `ActionP`, @@ -3670,6 +3655,6 @@ containers, and any type that supports the `<<` operator. For other types, it prints the raw bytes in the value and hopes that you the user can figure it out. -[Google Test's advanced guide](../../googletest/docs/AdvancedGuide.md#teaching-google-test-how-to-print-your-values) +[Google Test's advanced guide](../../googletest/docs/advanced.md#teaching-google-test-how-to-print-your-values) explains how to extend the printer to do a better job at printing your particular type than to dump the bytes.