128f6c2f2SEnji Cooper# gMock Cookbook 228f6c2f2SEnji Cooper 328f6c2f2SEnji CooperYou can find recipes for using gMock here. If you haven't yet, please read 428f6c2f2SEnji Cooper[the dummy guide](gmock_for_dummies.md) first to make sure you understand the 528f6c2f2SEnji Cooperbasics. 628f6c2f2SEnji Cooper 728f6c2f2SEnji Cooper{: .callout .note} 828f6c2f2SEnji Cooper**Note:** gMock lives in the `testing` name space. For readability, it is 928f6c2f2SEnji Cooperrecommended to write `using ::testing::Foo;` once in your file before using the 1028f6c2f2SEnji Coopername `Foo` defined by gMock. We omit such `using` statements in this section for 1128f6c2f2SEnji Cooperbrevity, but you should do it in your own code. 1228f6c2f2SEnji Cooper 1328f6c2f2SEnji Cooper## Creating Mock Classes 1428f6c2f2SEnji Cooper 1528f6c2f2SEnji CooperMock classes are defined as normal classes, using the `MOCK_METHOD` macro to 1628f6c2f2SEnji Coopergenerate mocked methods. The macro gets 3 or 4 parameters: 1728f6c2f2SEnji Cooper 1828f6c2f2SEnji Cooper```cpp 1928f6c2f2SEnji Cooperclass MyMock { 2028f6c2f2SEnji Cooper public: 2128f6c2f2SEnji Cooper MOCK_METHOD(ReturnType, MethodName, (Args...)); 2228f6c2f2SEnji Cooper MOCK_METHOD(ReturnType, MethodName, (Args...), (Specs...)); 2328f6c2f2SEnji Cooper}; 2428f6c2f2SEnji Cooper``` 2528f6c2f2SEnji Cooper 2628f6c2f2SEnji CooperThe first 3 parameters are simply the method declaration, split into 3 parts. 2728f6c2f2SEnji CooperThe 4th parameter accepts a closed list of qualifiers, which affect the 2828f6c2f2SEnji Coopergenerated method: 2928f6c2f2SEnji Cooper 3028f6c2f2SEnji Cooper* **`const`** - Makes the mocked method a `const` method. Required if 3128f6c2f2SEnji Cooper overriding a `const` method. 3228f6c2f2SEnji Cooper* **`override`** - Marks the method with `override`. Recommended if overriding 3328f6c2f2SEnji Cooper a `virtual` method. 3428f6c2f2SEnji Cooper* **`noexcept`** - Marks the method with `noexcept`. Required if overriding a 3528f6c2f2SEnji Cooper `noexcept` method. 3628f6c2f2SEnji Cooper* **`Calltype(...)`** - Sets the call type for the method (e.g. to 3728f6c2f2SEnji Cooper `STDMETHODCALLTYPE`), useful in Windows. 3828f6c2f2SEnji Cooper* **`ref(...)`** - Marks the method with the reference qualification 3928f6c2f2SEnji Cooper specified. Required if overriding a method that has reference 4028f6c2f2SEnji Cooper qualifications. Eg `ref(&)` or `ref(&&)`. 4128f6c2f2SEnji Cooper 4228f6c2f2SEnji Cooper### Dealing with unprotected commas 4328f6c2f2SEnji Cooper 4428f6c2f2SEnji CooperUnprotected commas, i.e. commas which are not surrounded by parentheses, prevent 4528f6c2f2SEnji Cooper`MOCK_METHOD` from parsing its arguments correctly: 4628f6c2f2SEnji Cooper 4728f6c2f2SEnji Cooper{: .bad} 4828f6c2f2SEnji Cooper```cpp 4928f6c2f2SEnji Cooperclass MockFoo { 5028f6c2f2SEnji Cooper public: 5128f6c2f2SEnji Cooper MOCK_METHOD(std::pair<bool, int>, GetPair, ()); // Won't compile! 5228f6c2f2SEnji Cooper MOCK_METHOD(bool, CheckMap, (std::map<int, double>, bool)); // Won't compile! 5328f6c2f2SEnji Cooper}; 5428f6c2f2SEnji Cooper``` 5528f6c2f2SEnji Cooper 5628f6c2f2SEnji CooperSolution 1 - wrap with parentheses: 5728f6c2f2SEnji Cooper 5828f6c2f2SEnji Cooper{: .good} 5928f6c2f2SEnji Cooper```cpp 6028f6c2f2SEnji Cooperclass MockFoo { 6128f6c2f2SEnji Cooper public: 6228f6c2f2SEnji Cooper MOCK_METHOD((std::pair<bool, int>), GetPair, ()); 6328f6c2f2SEnji Cooper MOCK_METHOD(bool, CheckMap, ((std::map<int, double>), bool)); 6428f6c2f2SEnji Cooper}; 6528f6c2f2SEnji Cooper``` 6628f6c2f2SEnji Cooper 6728f6c2f2SEnji CooperNote that wrapping a return or argument type with parentheses is, in general, 6828f6c2f2SEnji Cooperinvalid C++. `MOCK_METHOD` removes the parentheses. 6928f6c2f2SEnji Cooper 7028f6c2f2SEnji CooperSolution 2 - define an alias: 7128f6c2f2SEnji Cooper 7228f6c2f2SEnji Cooper{: .good} 7328f6c2f2SEnji Cooper```cpp 7428f6c2f2SEnji Cooperclass MockFoo { 7528f6c2f2SEnji Cooper public: 7628f6c2f2SEnji Cooper using BoolAndInt = std::pair<bool, int>; 7728f6c2f2SEnji Cooper MOCK_METHOD(BoolAndInt, GetPair, ()); 7828f6c2f2SEnji Cooper using MapIntDouble = std::map<int, double>; 7928f6c2f2SEnji Cooper MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool)); 8028f6c2f2SEnji Cooper}; 8128f6c2f2SEnji Cooper``` 8228f6c2f2SEnji Cooper 8328f6c2f2SEnji Cooper### Mocking Private or Protected Methods 8428f6c2f2SEnji Cooper 8528f6c2f2SEnji CooperYou must always put a mock method definition (`MOCK_METHOD`) in a `public:` 8628f6c2f2SEnji Coopersection of the mock class, regardless of the method being mocked being `public`, 8728f6c2f2SEnji Cooper`protected`, or `private` in the base class. This allows `ON_CALL` and 8828f6c2f2SEnji Cooper`EXPECT_CALL` to reference the mock function from outside of the mock class. 8928f6c2f2SEnji Cooper(Yes, C++ allows a subclass to change the access level of a virtual function in 9028f6c2f2SEnji Cooperthe base class.) Example: 9128f6c2f2SEnji Cooper 9228f6c2f2SEnji Cooper```cpp 9328f6c2f2SEnji Cooperclass Foo { 9428f6c2f2SEnji Cooper public: 9528f6c2f2SEnji Cooper ... 9628f6c2f2SEnji Cooper virtual bool Transform(Gadget* g) = 0; 9728f6c2f2SEnji Cooper 9828f6c2f2SEnji Cooper protected: 9928f6c2f2SEnji Cooper virtual void Resume(); 10028f6c2f2SEnji Cooper 10128f6c2f2SEnji Cooper private: 10228f6c2f2SEnji Cooper virtual int GetTimeOut(); 10328f6c2f2SEnji Cooper}; 10428f6c2f2SEnji Cooper 10528f6c2f2SEnji Cooperclass MockFoo : public Foo { 10628f6c2f2SEnji Cooper public: 10728f6c2f2SEnji Cooper ... 10828f6c2f2SEnji Cooper MOCK_METHOD(bool, Transform, (Gadget* g), (override)); 10928f6c2f2SEnji Cooper 11028f6c2f2SEnji Cooper // The following must be in the public section, even though the 11128f6c2f2SEnji Cooper // methods are protected or private in the base class. 11228f6c2f2SEnji Cooper MOCK_METHOD(void, Resume, (), (override)); 11328f6c2f2SEnji Cooper MOCK_METHOD(int, GetTimeOut, (), (override)); 11428f6c2f2SEnji Cooper}; 11528f6c2f2SEnji Cooper``` 11628f6c2f2SEnji Cooper 11728f6c2f2SEnji Cooper### Mocking Overloaded Methods 11828f6c2f2SEnji Cooper 11928f6c2f2SEnji CooperYou can mock overloaded functions as usual. No special attention is required: 12028f6c2f2SEnji Cooper 12128f6c2f2SEnji Cooper```cpp 12228f6c2f2SEnji Cooperclass Foo { 12328f6c2f2SEnji Cooper ... 12428f6c2f2SEnji Cooper 12528f6c2f2SEnji Cooper // Must be virtual as we'll inherit from Foo. 12628f6c2f2SEnji Cooper virtual ~Foo(); 12728f6c2f2SEnji Cooper 12828f6c2f2SEnji Cooper // Overloaded on the types and/or numbers of arguments. 12928f6c2f2SEnji Cooper virtual int Add(Element x); 13028f6c2f2SEnji Cooper virtual int Add(int times, Element x); 13128f6c2f2SEnji Cooper 13228f6c2f2SEnji Cooper // Overloaded on the const-ness of this object. 13328f6c2f2SEnji Cooper virtual Bar& GetBar(); 13428f6c2f2SEnji Cooper virtual const Bar& GetBar() const; 13528f6c2f2SEnji Cooper}; 13628f6c2f2SEnji Cooper 13728f6c2f2SEnji Cooperclass MockFoo : public Foo { 13828f6c2f2SEnji Cooper ... 13928f6c2f2SEnji Cooper MOCK_METHOD(int, Add, (Element x), (override)); 14028f6c2f2SEnji Cooper MOCK_METHOD(int, Add, (int times, Element x), (override)); 14128f6c2f2SEnji Cooper 14228f6c2f2SEnji Cooper MOCK_METHOD(Bar&, GetBar, (), (override)); 14328f6c2f2SEnji Cooper MOCK_METHOD(const Bar&, GetBar, (), (const, override)); 14428f6c2f2SEnji Cooper}; 14528f6c2f2SEnji Cooper``` 14628f6c2f2SEnji Cooper 14728f6c2f2SEnji Cooper{: .callout .note} 14828f6c2f2SEnji Cooper**Note:** if you don't mock all versions of the overloaded method, the compiler 14928f6c2f2SEnji Cooperwill give you a warning about some methods in the base class being hidden. To 15028f6c2f2SEnji Cooperfix that, use `using` to bring them in scope: 15128f6c2f2SEnji Cooper 15228f6c2f2SEnji Cooper```cpp 15328f6c2f2SEnji Cooperclass MockFoo : public Foo { 15428f6c2f2SEnji Cooper ... 15528f6c2f2SEnji Cooper using Foo::Add; 15628f6c2f2SEnji Cooper MOCK_METHOD(int, Add, (Element x), (override)); 15728f6c2f2SEnji Cooper // We don't want to mock int Add(int times, Element x); 15828f6c2f2SEnji Cooper ... 15928f6c2f2SEnji Cooper}; 16028f6c2f2SEnji Cooper``` 16128f6c2f2SEnji Cooper 16228f6c2f2SEnji Cooper### Mocking Class Templates 16328f6c2f2SEnji Cooper 16428f6c2f2SEnji CooperYou can mock class templates just like any class. 16528f6c2f2SEnji Cooper 16628f6c2f2SEnji Cooper```cpp 16728f6c2f2SEnji Coopertemplate <typename Elem> 16828f6c2f2SEnji Cooperclass StackInterface { 16928f6c2f2SEnji Cooper ... 17028f6c2f2SEnji Cooper // Must be virtual as we'll inherit from StackInterface. 17128f6c2f2SEnji Cooper virtual ~StackInterface(); 17228f6c2f2SEnji Cooper 17328f6c2f2SEnji Cooper virtual int GetSize() const = 0; 17428f6c2f2SEnji Cooper virtual void Push(const Elem& x) = 0; 17528f6c2f2SEnji Cooper}; 17628f6c2f2SEnji Cooper 17728f6c2f2SEnji Coopertemplate <typename Elem> 17828f6c2f2SEnji Cooperclass MockStack : public StackInterface<Elem> { 17928f6c2f2SEnji Cooper ... 18028f6c2f2SEnji Cooper MOCK_METHOD(int, GetSize, (), (override)); 18128f6c2f2SEnji Cooper MOCK_METHOD(void, Push, (const Elem& x), (override)); 18228f6c2f2SEnji Cooper}; 18328f6c2f2SEnji Cooper``` 18428f6c2f2SEnji Cooper 18528f6c2f2SEnji Cooper### Mocking Non-virtual Methods {#MockingNonVirtualMethods} 18628f6c2f2SEnji Cooper 18728f6c2f2SEnji CoopergMock can mock non-virtual functions to be used in Hi-perf dependency injection. 18828f6c2f2SEnji Cooper 18928f6c2f2SEnji CooperIn this case, instead of sharing a common base class with the real class, your 19028f6c2f2SEnji Coopermock class will be *unrelated* to the real class, but contain methods with the 19128f6c2f2SEnji Coopersame signatures. The syntax for mocking non-virtual methods is the *same* as 19228f6c2f2SEnji Coopermocking virtual methods (just don't add `override`): 19328f6c2f2SEnji Cooper 19428f6c2f2SEnji Cooper```cpp 19528f6c2f2SEnji Cooper// A simple packet stream class. None of its members is virtual. 19628f6c2f2SEnji Cooperclass ConcretePacketStream { 19728f6c2f2SEnji Cooper public: 19828f6c2f2SEnji Cooper void AppendPacket(Packet* new_packet); 19928f6c2f2SEnji Cooper const Packet* GetPacket(size_t packet_number) const; 20028f6c2f2SEnji Cooper size_t NumberOfPackets() const; 20128f6c2f2SEnji Cooper ... 20228f6c2f2SEnji Cooper}; 20328f6c2f2SEnji Cooper 20428f6c2f2SEnji Cooper// A mock packet stream class. It inherits from no other, but defines 20528f6c2f2SEnji Cooper// GetPacket() and NumberOfPackets(). 20628f6c2f2SEnji Cooperclass MockPacketStream { 20728f6c2f2SEnji Cooper public: 20828f6c2f2SEnji Cooper MOCK_METHOD(const Packet*, GetPacket, (size_t packet_number), (const)); 20928f6c2f2SEnji Cooper MOCK_METHOD(size_t, NumberOfPackets, (), (const)); 21028f6c2f2SEnji Cooper ... 21128f6c2f2SEnji Cooper}; 21228f6c2f2SEnji Cooper``` 21328f6c2f2SEnji Cooper 21428f6c2f2SEnji CooperNote that the mock class doesn't define `AppendPacket()`, unlike the real class. 21528f6c2f2SEnji CooperThat's fine as long as the test doesn't need to call it. 21628f6c2f2SEnji Cooper 21728f6c2f2SEnji CooperNext, you need a way to say that you want to use `ConcretePacketStream` in 21828f6c2f2SEnji Cooperproduction code, and use `MockPacketStream` in tests. Since the functions are 21928f6c2f2SEnji Coopernot virtual and the two classes are unrelated, you must specify your choice at 22028f6c2f2SEnji Cooper*compile time* (as opposed to run time). 22128f6c2f2SEnji Cooper 22228f6c2f2SEnji CooperOne way to do it is to templatize your code that needs to use a packet stream. 22328f6c2f2SEnji CooperMore specifically, you will give your code a template type argument for the type 22428f6c2f2SEnji Cooperof the packet stream. In production, you will instantiate your template with 22528f6c2f2SEnji Cooper`ConcretePacketStream` as the type argument. In tests, you will instantiate the 22628f6c2f2SEnji Coopersame template with `MockPacketStream`. For example, you may write: 22728f6c2f2SEnji Cooper 22828f6c2f2SEnji Cooper```cpp 22928f6c2f2SEnji Coopertemplate <class PacketStream> 23028f6c2f2SEnji Coopervoid CreateConnection(PacketStream* stream) { ... } 23128f6c2f2SEnji Cooper 23228f6c2f2SEnji Coopertemplate <class PacketStream> 23328f6c2f2SEnji Cooperclass PacketReader { 23428f6c2f2SEnji Cooper public: 23528f6c2f2SEnji Cooper void ReadPackets(PacketStream* stream, size_t packet_num); 23628f6c2f2SEnji Cooper}; 23728f6c2f2SEnji Cooper``` 23828f6c2f2SEnji Cooper 23928f6c2f2SEnji CooperThen you can use `CreateConnection<ConcretePacketStream>()` and 24028f6c2f2SEnji Cooper`PacketReader<ConcretePacketStream>` in production code, and use 24128f6c2f2SEnji Cooper`CreateConnection<MockPacketStream>()` and `PacketReader<MockPacketStream>` in 24228f6c2f2SEnji Coopertests. 24328f6c2f2SEnji Cooper 24428f6c2f2SEnji Cooper```cpp 24528f6c2f2SEnji Cooper MockPacketStream mock_stream; 24628f6c2f2SEnji Cooper EXPECT_CALL(mock_stream, ...)...; 24728f6c2f2SEnji Cooper .. set more expectations on mock_stream ... 24828f6c2f2SEnji Cooper PacketReader<MockPacketStream> reader(&mock_stream); 24928f6c2f2SEnji Cooper ... exercise reader ... 25028f6c2f2SEnji Cooper``` 25128f6c2f2SEnji Cooper 25228f6c2f2SEnji Cooper### Mocking Free Functions 25328f6c2f2SEnji Cooper 25428f6c2f2SEnji CooperIt is not possible to directly mock a free function (i.e. a C-style function or 25528f6c2f2SEnji Coopera static method). If you need to, you can rewrite your code to use an interface 25628f6c2f2SEnji Cooper(abstract class). 25728f6c2f2SEnji Cooper 25828f6c2f2SEnji CooperInstead of calling a free function (say, `OpenFile`) directly, introduce an 25928f6c2f2SEnji Cooperinterface for it and have a concrete subclass that calls the free function: 26028f6c2f2SEnji Cooper 26128f6c2f2SEnji Cooper```cpp 26228f6c2f2SEnji Cooperclass FileInterface { 26328f6c2f2SEnji Cooper public: 26428f6c2f2SEnji Cooper ... 26528f6c2f2SEnji Cooper virtual bool Open(const char* path, const char* mode) = 0; 26628f6c2f2SEnji Cooper}; 26728f6c2f2SEnji Cooper 26828f6c2f2SEnji Cooperclass File : public FileInterface { 26928f6c2f2SEnji Cooper public: 27028f6c2f2SEnji Cooper ... 27128f6c2f2SEnji Cooper bool Open(const char* path, const char* mode) override { 27228f6c2f2SEnji Cooper return OpenFile(path, mode); 27328f6c2f2SEnji Cooper } 27428f6c2f2SEnji Cooper}; 27528f6c2f2SEnji Cooper``` 27628f6c2f2SEnji Cooper 27728f6c2f2SEnji CooperYour code should talk to `FileInterface` to open a file. Now it's easy to mock 27828f6c2f2SEnji Cooperout the function. 27928f6c2f2SEnji Cooper 28028f6c2f2SEnji CooperThis may seem like a lot of hassle, but in practice you often have multiple 28128f6c2f2SEnji Cooperrelated functions that you can put in the same interface, so the per-function 28228f6c2f2SEnji Coopersyntactic overhead will be much lower. 28328f6c2f2SEnji Cooper 28428f6c2f2SEnji CooperIf you are concerned about the performance overhead incurred by virtual 28528f6c2f2SEnji Cooperfunctions, and profiling confirms your concern, you can combine this with the 28628f6c2f2SEnji Cooperrecipe for [mocking non-virtual methods](#MockingNonVirtualMethods). 28728f6c2f2SEnji Cooper 28828f6c2f2SEnji CooperAlternatively, instead of introducing a new interface, you can rewrite your code 28928f6c2f2SEnji Cooperto accept a std::function instead of the free function, and then use 29028f6c2f2SEnji Cooper[MockFunction](#MockFunction) to mock the std::function. 29128f6c2f2SEnji Cooper 29228f6c2f2SEnji Cooper### Old-Style `MOCK_METHODn` Macros 29328f6c2f2SEnji Cooper 29428f6c2f2SEnji CooperBefore the generic `MOCK_METHOD` macro 29528f6c2f2SEnji Cooper[was introduced in 2018](https://github.com/google/googletest/commit/c5f08bf91944ce1b19bcf414fa1760e69d20afc2), 29628f6c2f2SEnji Coopermocks where created using a family of macros collectively called `MOCK_METHODn`. 29728f6c2f2SEnji CooperThese macros are still supported, though migration to the new `MOCK_METHOD` is 29828f6c2f2SEnji Cooperrecommended. 29928f6c2f2SEnji Cooper 30028f6c2f2SEnji CooperThe macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`: 30128f6c2f2SEnji Cooper 30228f6c2f2SEnji Cooper* The general structure is `MOCK_METHODn(MethodName, ReturnType(Args))`, 30328f6c2f2SEnji Cooper instead of `MOCK_METHOD(ReturnType, MethodName, (Args))`. 30428f6c2f2SEnji Cooper* The number `n` must equal the number of arguments. 30528f6c2f2SEnji Cooper* When mocking a const method, one must use `MOCK_CONST_METHODn`. 30628f6c2f2SEnji Cooper* When mocking a class template, the macro name must be suffixed with `_T`. 30728f6c2f2SEnji Cooper* In order to specify the call type, the macro name must be suffixed with 30828f6c2f2SEnji Cooper `_WITH_CALLTYPE`, and the call type is the first macro argument. 30928f6c2f2SEnji Cooper 31028f6c2f2SEnji CooperOld macros and their new equivalents: 31128f6c2f2SEnji Cooper 31228f6c2f2SEnji Cooper<table> 31328f6c2f2SEnji Cooper <tr><th colspan=2>Simple</th></tr> 31428f6c2f2SEnji Cooper <tr> 31528f6c2f2SEnji Cooper <td>Old</td> 31628f6c2f2SEnji Cooper <td><code>MOCK_METHOD1(Foo, bool(int))</code></td> 31728f6c2f2SEnji Cooper </tr> 31828f6c2f2SEnji Cooper <tr> 31928f6c2f2SEnji Cooper <td>New</td> 32028f6c2f2SEnji Cooper <td><code>MOCK_METHOD(bool, Foo, (int))</code></td> 32128f6c2f2SEnji Cooper </tr> 32228f6c2f2SEnji Cooper 32328f6c2f2SEnji Cooper <tr><th colspan=2>Const Method</th></tr> 32428f6c2f2SEnji Cooper <tr> 32528f6c2f2SEnji Cooper <td>Old</td> 32628f6c2f2SEnji Cooper <td><code>MOCK_CONST_METHOD1(Foo, bool(int))</code></td> 32728f6c2f2SEnji Cooper </tr> 32828f6c2f2SEnji Cooper <tr> 32928f6c2f2SEnji Cooper <td>New</td> 33028f6c2f2SEnji Cooper <td><code>MOCK_METHOD(bool, Foo, (int), (const))</code></td> 33128f6c2f2SEnji Cooper </tr> 33228f6c2f2SEnji Cooper 33328f6c2f2SEnji Cooper <tr><th colspan=2>Method in a Class Template</th></tr> 33428f6c2f2SEnji Cooper <tr> 33528f6c2f2SEnji Cooper <td>Old</td> 33628f6c2f2SEnji Cooper <td><code>MOCK_METHOD1_T(Foo, bool(int))</code></td> 33728f6c2f2SEnji Cooper </tr> 33828f6c2f2SEnji Cooper <tr> 33928f6c2f2SEnji Cooper <td>New</td> 34028f6c2f2SEnji Cooper <td><code>MOCK_METHOD(bool, Foo, (int))</code></td> 34128f6c2f2SEnji Cooper </tr> 34228f6c2f2SEnji Cooper 34328f6c2f2SEnji Cooper <tr><th colspan=2>Const Method in a Class Template</th></tr> 34428f6c2f2SEnji Cooper <tr> 34528f6c2f2SEnji Cooper <td>Old</td> 34628f6c2f2SEnji Cooper <td><code>MOCK_CONST_METHOD1_T(Foo, bool(int))</code></td> 34728f6c2f2SEnji Cooper </tr> 34828f6c2f2SEnji Cooper <tr> 34928f6c2f2SEnji Cooper <td>New</td> 35028f6c2f2SEnji Cooper <td><code>MOCK_METHOD(bool, Foo, (int), (const))</code></td> 35128f6c2f2SEnji Cooper </tr> 35228f6c2f2SEnji Cooper 35328f6c2f2SEnji Cooper <tr><th colspan=2>Method with Call Type</th></tr> 35428f6c2f2SEnji Cooper <tr> 35528f6c2f2SEnji Cooper <td>Old</td> 35628f6c2f2SEnji Cooper <td><code>MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td> 35728f6c2f2SEnji Cooper </tr> 35828f6c2f2SEnji Cooper <tr> 35928f6c2f2SEnji Cooper <td>New</td> 36028f6c2f2SEnji Cooper <td><code>MOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))</code></td> 36128f6c2f2SEnji Cooper </tr> 36228f6c2f2SEnji Cooper 36328f6c2f2SEnji Cooper <tr><th colspan=2>Const Method with Call Type</th></tr> 36428f6c2f2SEnji Cooper <tr> 36528f6c2f2SEnji Cooper <td>Old</td> 36628f6c2f2SEnji Cooper <td><code>MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td> 36728f6c2f2SEnji Cooper </tr> 36828f6c2f2SEnji Cooper <tr> 36928f6c2f2SEnji Cooper <td>New</td> 37028f6c2f2SEnji Cooper <td><code>MOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))</code></td> 37128f6c2f2SEnji Cooper </tr> 37228f6c2f2SEnji Cooper 37328f6c2f2SEnji Cooper <tr><th colspan=2>Method with Call Type in a Class Template</th></tr> 37428f6c2f2SEnji Cooper <tr> 37528f6c2f2SEnji Cooper <td>Old</td> 37628f6c2f2SEnji Cooper <td><code>MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td> 37728f6c2f2SEnji Cooper </tr> 37828f6c2f2SEnji Cooper <tr> 37928f6c2f2SEnji Cooper <td>New</td> 38028f6c2f2SEnji Cooper <td><code>MOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))</code></td> 38128f6c2f2SEnji Cooper </tr> 38228f6c2f2SEnji Cooper 38328f6c2f2SEnji Cooper <tr><th colspan=2>Const Method with Call Type in a Class Template</th></tr> 38428f6c2f2SEnji Cooper <tr> 38528f6c2f2SEnji Cooper <td>Old</td> 38628f6c2f2SEnji Cooper <td><code>MOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td> 38728f6c2f2SEnji Cooper </tr> 38828f6c2f2SEnji Cooper <tr> 38928f6c2f2SEnji Cooper <td>New</td> 39028f6c2f2SEnji Cooper <td><code>MOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))</code></td> 39128f6c2f2SEnji Cooper </tr> 39228f6c2f2SEnji Cooper</table> 39328f6c2f2SEnji Cooper 39428f6c2f2SEnji Cooper### The Nice, the Strict, and the Naggy {#NiceStrictNaggy} 39528f6c2f2SEnji Cooper 39628f6c2f2SEnji CooperIf a mock method has no `EXPECT_CALL` spec but is called, we say that it's an 39728f6c2f2SEnji Cooper"uninteresting call", and the default action (which can be specified using 39828f6c2f2SEnji Cooper`ON_CALL()`) of the method will be taken. Currently, an uninteresting call will 39928f6c2f2SEnji Cooperalso by default cause gMock to print a warning. 40028f6c2f2SEnji Cooper 40128f6c2f2SEnji CooperHowever, sometimes you may want to ignore these uninteresting calls, and 40228f6c2f2SEnji Coopersometimes you may want to treat them as errors. gMock lets you make the decision 40328f6c2f2SEnji Cooperon a per-mock-object basis. 40428f6c2f2SEnji Cooper 40528f6c2f2SEnji CooperSuppose your test uses a mock class `MockFoo`: 40628f6c2f2SEnji Cooper 40728f6c2f2SEnji Cooper```cpp 40828f6c2f2SEnji CooperTEST(...) { 40928f6c2f2SEnji Cooper MockFoo mock_foo; 41028f6c2f2SEnji Cooper EXPECT_CALL(mock_foo, DoThis()); 41128f6c2f2SEnji Cooper ... code that uses mock_foo ... 41228f6c2f2SEnji Cooper} 41328f6c2f2SEnji Cooper``` 41428f6c2f2SEnji Cooper 41528f6c2f2SEnji CooperIf a method of `mock_foo` other than `DoThis()` is called, you will get a 41628f6c2f2SEnji Cooperwarning. However, if you rewrite your test to use `NiceMock<MockFoo>` instead, 41728f6c2f2SEnji Cooperyou can suppress the warning: 41828f6c2f2SEnji Cooper 41928f6c2f2SEnji Cooper```cpp 42028f6c2f2SEnji Cooperusing ::testing::NiceMock; 42128f6c2f2SEnji Cooper 42228f6c2f2SEnji CooperTEST(...) { 42328f6c2f2SEnji Cooper NiceMock<MockFoo> mock_foo; 42428f6c2f2SEnji Cooper EXPECT_CALL(mock_foo, DoThis()); 42528f6c2f2SEnji Cooper ... code that uses mock_foo ... 42628f6c2f2SEnji Cooper} 42728f6c2f2SEnji Cooper``` 42828f6c2f2SEnji Cooper 42928f6c2f2SEnji Cooper`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used wherever 43028f6c2f2SEnji Cooper`MockFoo` is accepted. 43128f6c2f2SEnji Cooper 43228f6c2f2SEnji CooperIt also works if `MockFoo`'s constructor takes some arguments, as 43328f6c2f2SEnji Cooper`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors: 43428f6c2f2SEnji Cooper 43528f6c2f2SEnji Cooper```cpp 43628f6c2f2SEnji Cooperusing ::testing::NiceMock; 43728f6c2f2SEnji Cooper 43828f6c2f2SEnji CooperTEST(...) { 43928f6c2f2SEnji Cooper NiceMock<MockFoo> mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). 44028f6c2f2SEnji Cooper EXPECT_CALL(mock_foo, DoThis()); 44128f6c2f2SEnji Cooper ... code that uses mock_foo ... 44228f6c2f2SEnji Cooper} 44328f6c2f2SEnji Cooper``` 44428f6c2f2SEnji Cooper 44528f6c2f2SEnji CooperThe usage of `StrictMock` is similar, except that it makes all uninteresting 44628f6c2f2SEnji Coopercalls failures: 44728f6c2f2SEnji Cooper 44828f6c2f2SEnji Cooper```cpp 44928f6c2f2SEnji Cooperusing ::testing::StrictMock; 45028f6c2f2SEnji Cooper 45128f6c2f2SEnji CooperTEST(...) { 45228f6c2f2SEnji Cooper StrictMock<MockFoo> mock_foo; 45328f6c2f2SEnji Cooper EXPECT_CALL(mock_foo, DoThis()); 45428f6c2f2SEnji Cooper ... code that uses mock_foo ... 45528f6c2f2SEnji Cooper 45628f6c2f2SEnji Cooper // The test will fail if a method of mock_foo other than DoThis() 45728f6c2f2SEnji Cooper // is called. 45828f6c2f2SEnji Cooper} 45928f6c2f2SEnji Cooper``` 46028f6c2f2SEnji Cooper 46128f6c2f2SEnji Cooper{: .callout .note} 46228f6c2f2SEnji CooperNOTE: `NiceMock` and `StrictMock` only affects *uninteresting* calls (calls of 46328f6c2f2SEnji Cooper*methods* with no expectations); they do not affect *unexpected* calls (calls of 46428f6c2f2SEnji Coopermethods with expectations, but they don't match). See 46528f6c2f2SEnji Cooper[Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected). 46628f6c2f2SEnji Cooper 46728f6c2f2SEnji CooperThere are some caveats though (sadly they are side effects of C++'s 46828f6c2f2SEnji Cooperlimitations): 46928f6c2f2SEnji Cooper 47028f6c2f2SEnji Cooper1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods 47128f6c2f2SEnji Cooper defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class. 47228f6c2f2SEnji Cooper If a mock method is defined in a **base class** of `MockFoo`, the "nice" or 47328f6c2f2SEnji Cooper "strict" modifier may not affect it, depending on the compiler. In 47428f6c2f2SEnji Cooper particular, nesting `NiceMock` and `StrictMock` (e.g. 47528f6c2f2SEnji Cooper `NiceMock<StrictMock<MockFoo> >`) is **not** supported. 47628f6c2f2SEnji Cooper2. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` may not work correctly if the 47728f6c2f2SEnji Cooper destructor of `MockFoo` is not virtual. We would like to fix this, but it 47828f6c2f2SEnji Cooper requires cleaning up existing tests. 47928f6c2f2SEnji Cooper 48028f6c2f2SEnji CooperFinally, you should be **very cautious** about when to use naggy or strict 48128f6c2f2SEnji Coopermocks, as they tend to make tests more brittle and harder to maintain. When you 48228f6c2f2SEnji Cooperrefactor your code without changing its externally visible behavior, ideally you 48328f6c2f2SEnji Coopershouldn't need to update any tests. If your code interacts with a naggy mock, 48428f6c2f2SEnji Cooperhowever, you may start to get spammed with warnings as the result of your 48528f6c2f2SEnji Cooperchange. Worse, if your code interacts with a strict mock, your tests may start 48628f6c2f2SEnji Cooperto fail and you'll be forced to fix them. Our general recommendation is to use 48728f6c2f2SEnji Coopernice mocks (not yet the default) most of the time, use naggy mocks (the current 48828f6c2f2SEnji Cooperdefault) when developing or debugging tests, and use strict mocks only as the 48928f6c2f2SEnji Cooperlast resort. 49028f6c2f2SEnji Cooper 49128f6c2f2SEnji Cooper### Simplifying the Interface without Breaking Existing Code {#SimplerInterfaces} 49228f6c2f2SEnji Cooper 49328f6c2f2SEnji CooperSometimes a method has a long list of arguments that is mostly uninteresting. 49428f6c2f2SEnji CooperFor example: 49528f6c2f2SEnji Cooper 49628f6c2f2SEnji Cooper```cpp 49728f6c2f2SEnji Cooperclass LogSink { 49828f6c2f2SEnji Cooper public: 49928f6c2f2SEnji Cooper ... 50028f6c2f2SEnji Cooper virtual void send(LogSeverity severity, const char* full_filename, 50128f6c2f2SEnji Cooper const char* base_filename, int line, 50228f6c2f2SEnji Cooper const struct tm* tm_time, 50328f6c2f2SEnji Cooper const char* message, size_t message_len) = 0; 50428f6c2f2SEnji Cooper}; 50528f6c2f2SEnji Cooper``` 50628f6c2f2SEnji Cooper 50728f6c2f2SEnji CooperThis method's argument list is lengthy and hard to work with (the `message` 50828f6c2f2SEnji Cooperargument is not even 0-terminated). If we mock it as is, using the mock will be 50928f6c2f2SEnji Cooperawkward. If, however, we try to simplify this interface, we'll need to fix all 51028f6c2f2SEnji Cooperclients depending on it, which is often infeasible. 51128f6c2f2SEnji Cooper 51228f6c2f2SEnji CooperThe trick is to redispatch the method in the mock class: 51328f6c2f2SEnji Cooper 51428f6c2f2SEnji Cooper```cpp 51528f6c2f2SEnji Cooperclass ScopedMockLog : public LogSink { 51628f6c2f2SEnji Cooper public: 51728f6c2f2SEnji Cooper ... 51828f6c2f2SEnji Cooper void send(LogSeverity severity, const char* full_filename, 51928f6c2f2SEnji Cooper const char* base_filename, int line, const tm* tm_time, 52028f6c2f2SEnji Cooper const char* message, size_t message_len) override { 52128f6c2f2SEnji Cooper // We are only interested in the log severity, full file name, and 52228f6c2f2SEnji Cooper // log message. 52328f6c2f2SEnji Cooper Log(severity, full_filename, std::string(message, message_len)); 52428f6c2f2SEnji Cooper } 52528f6c2f2SEnji Cooper 52628f6c2f2SEnji Cooper // Implements the mock method: 52728f6c2f2SEnji Cooper // 52828f6c2f2SEnji Cooper // void Log(LogSeverity severity, 52928f6c2f2SEnji Cooper // const string& file_path, 53028f6c2f2SEnji Cooper // const string& message); 53128f6c2f2SEnji Cooper MOCK_METHOD(void, Log, 53228f6c2f2SEnji Cooper (LogSeverity severity, const string& file_path, 53328f6c2f2SEnji Cooper const string& message)); 53428f6c2f2SEnji Cooper}; 53528f6c2f2SEnji Cooper``` 53628f6c2f2SEnji Cooper 53728f6c2f2SEnji CooperBy defining a new mock method with a trimmed argument list, we make the mock 53828f6c2f2SEnji Cooperclass more user-friendly. 53928f6c2f2SEnji Cooper 54028f6c2f2SEnji CooperThis technique may also be applied to make overloaded methods more amenable to 54128f6c2f2SEnji Coopermocking. For example, when overloads have been used to implement default 54228f6c2f2SEnji Cooperarguments: 54328f6c2f2SEnji Cooper 54428f6c2f2SEnji Cooper```cpp 54528f6c2f2SEnji Cooperclass MockTurtleFactory : public TurtleFactory { 54628f6c2f2SEnji Cooper public: 54728f6c2f2SEnji Cooper Turtle* MakeTurtle(int length, int weight) override { ... } 54828f6c2f2SEnji Cooper Turtle* MakeTurtle(int length, int weight, int speed) override { ... } 54928f6c2f2SEnji Cooper 55028f6c2f2SEnji Cooper // the above methods delegate to this one: 55128f6c2f2SEnji Cooper MOCK_METHOD(Turtle*, DoMakeTurtle, ()); 55228f6c2f2SEnji Cooper}; 55328f6c2f2SEnji Cooper``` 55428f6c2f2SEnji Cooper 55528f6c2f2SEnji CooperThis allows tests that don't care which overload was invoked to avoid specifying 55628f6c2f2SEnji Cooperargument matchers: 55728f6c2f2SEnji Cooper 55828f6c2f2SEnji Cooper```cpp 55928f6c2f2SEnji CooperON_CALL(factory, DoMakeTurtle) 56028f6c2f2SEnji Cooper .WillByDefault(Return(MakeMockTurtle())); 56128f6c2f2SEnji Cooper``` 56228f6c2f2SEnji Cooper 56328f6c2f2SEnji Cooper### Alternative to Mocking Concrete Classes 56428f6c2f2SEnji Cooper 56528f6c2f2SEnji CooperOften you may find yourself using classes that don't implement interfaces. In 56628f6c2f2SEnji Cooperorder to test your code that uses such a class (let's call it `Concrete`), you 56728f6c2f2SEnji Coopermay be tempted to make the methods of `Concrete` virtual and then mock it. 56828f6c2f2SEnji Cooper 56928f6c2f2SEnji CooperTry not to do that. 57028f6c2f2SEnji Cooper 57128f6c2f2SEnji CooperMaking a non-virtual function virtual is a big decision. It creates an extension 57228f6c2f2SEnji Cooperpoint where subclasses can tweak your class' behavior. This weakens your control 57328f6c2f2SEnji Cooperon the class because now it's harder to maintain the class invariants. You 57428f6c2f2SEnji Coopershould make a function virtual only when there is a valid reason for a subclass 57528f6c2f2SEnji Cooperto override it. 57628f6c2f2SEnji Cooper 57728f6c2f2SEnji CooperMocking concrete classes directly is problematic as it creates a tight coupling 57828f6c2f2SEnji Cooperbetween the class and the tests - any small change in the class may invalidate 57928f6c2f2SEnji Cooperyour tests and make test maintenance a pain. 58028f6c2f2SEnji Cooper 58128f6c2f2SEnji CooperTo avoid such problems, many programmers have been practicing "coding to 58228f6c2f2SEnji Cooperinterfaces": instead of talking to the `Concrete` class, your code would define 58328f6c2f2SEnji Cooperan interface and talk to it. Then you implement that interface as an adaptor on 58428f6c2f2SEnji Coopertop of `Concrete`. In tests, you can easily mock that interface to observe how 58528f6c2f2SEnji Cooperyour code is doing. 58628f6c2f2SEnji Cooper 58728f6c2f2SEnji CooperThis technique incurs some overhead: 58828f6c2f2SEnji Cooper 58928f6c2f2SEnji Cooper* You pay the cost of virtual function calls (usually not a problem). 59028f6c2f2SEnji Cooper* There is more abstraction for the programmers to learn. 59128f6c2f2SEnji Cooper 59228f6c2f2SEnji CooperHowever, it can also bring significant benefits in addition to better 59328f6c2f2SEnji Coopertestability: 59428f6c2f2SEnji Cooper 59528f6c2f2SEnji Cooper* `Concrete`'s API may not fit your problem domain very well, as you may not 59628f6c2f2SEnji Cooper be the only client it tries to serve. By designing your own interface, you 59728f6c2f2SEnji Cooper have a chance to tailor it to your need - you may add higher-level 59828f6c2f2SEnji Cooper functionalities, rename stuff, etc instead of just trimming the class. This 59928f6c2f2SEnji Cooper allows you to write your code (user of the interface) in a more natural way, 60028f6c2f2SEnji Cooper which means it will be more readable, more maintainable, and you'll be more 60128f6c2f2SEnji Cooper productive. 60228f6c2f2SEnji Cooper* If `Concrete`'s implementation ever has to change, you don't have to rewrite 60328f6c2f2SEnji Cooper everywhere it is used. Instead, you can absorb the change in your 60428f6c2f2SEnji Cooper implementation of the interface, and your other code and tests will be 60528f6c2f2SEnji Cooper insulated from this change. 60628f6c2f2SEnji Cooper 60728f6c2f2SEnji CooperSome people worry that if everyone is practicing this technique, they will end 60828f6c2f2SEnji Cooperup writing lots of redundant code. This concern is totally understandable. 60928f6c2f2SEnji CooperHowever, there are two reasons why it may not be the case: 61028f6c2f2SEnji Cooper 61128f6c2f2SEnji Cooper* Different projects may need to use `Concrete` in different ways, so the best 61228f6c2f2SEnji Cooper interfaces for them will be different. Therefore, each of them will have its 61328f6c2f2SEnji Cooper own domain-specific interface on top of `Concrete`, and they will not be the 61428f6c2f2SEnji Cooper same code. 61528f6c2f2SEnji Cooper* If enough projects want to use the same interface, they can always share it, 61628f6c2f2SEnji Cooper just like they have been sharing `Concrete`. You can check in the interface 61728f6c2f2SEnji Cooper and the adaptor somewhere near `Concrete` (perhaps in a `contrib` 61828f6c2f2SEnji Cooper sub-directory) and let many projects use it. 61928f6c2f2SEnji Cooper 62028f6c2f2SEnji CooperYou need to weigh the pros and cons carefully for your particular problem, but 62128f6c2f2SEnji CooperI'd like to assure you that the Java community has been practicing this for a 62228f6c2f2SEnji Cooperlong time and it's a proven effective technique applicable in a wide variety of 62328f6c2f2SEnji Coopersituations. :-) 62428f6c2f2SEnji Cooper 62528f6c2f2SEnji Cooper### Delegating Calls to a Fake {#DelegatingToFake} 62628f6c2f2SEnji Cooper 62728f6c2f2SEnji CooperSome times you have a non-trivial fake implementation of an interface. For 62828f6c2f2SEnji Cooperexample: 62928f6c2f2SEnji Cooper 63028f6c2f2SEnji Cooper```cpp 63128f6c2f2SEnji Cooperclass Foo { 63228f6c2f2SEnji Cooper public: 63328f6c2f2SEnji Cooper virtual ~Foo() {} 63428f6c2f2SEnji Cooper virtual char DoThis(int n) = 0; 63528f6c2f2SEnji Cooper virtual void DoThat(const char* s, int* p) = 0; 63628f6c2f2SEnji Cooper}; 63728f6c2f2SEnji Cooper 63828f6c2f2SEnji Cooperclass FakeFoo : public Foo { 63928f6c2f2SEnji Cooper public: 64028f6c2f2SEnji Cooper char DoThis(int n) override { 64128f6c2f2SEnji Cooper return (n > 0) ? '+' : 64228f6c2f2SEnji Cooper (n < 0) ? '-' : '0'; 64328f6c2f2SEnji Cooper } 64428f6c2f2SEnji Cooper 64528f6c2f2SEnji Cooper void DoThat(const char* s, int* p) override { 64628f6c2f2SEnji Cooper *p = strlen(s); 64728f6c2f2SEnji Cooper } 64828f6c2f2SEnji Cooper}; 64928f6c2f2SEnji Cooper``` 65028f6c2f2SEnji Cooper 65128f6c2f2SEnji CooperNow you want to mock this interface such that you can set expectations on it. 65228f6c2f2SEnji CooperHowever, you also want to use `FakeFoo` for the default behavior, as duplicating 65328f6c2f2SEnji Cooperit in the mock object is, well, a lot of work. 65428f6c2f2SEnji Cooper 65528f6c2f2SEnji CooperWhen you define the mock class using gMock, you can have it delegate its default 65628f6c2f2SEnji Cooperaction to a fake class you already have, using this pattern: 65728f6c2f2SEnji Cooper 65828f6c2f2SEnji Cooper```cpp 65928f6c2f2SEnji Cooperclass MockFoo : public Foo { 66028f6c2f2SEnji Cooper public: 66128f6c2f2SEnji Cooper // Normal mock method definitions using gMock. 66228f6c2f2SEnji Cooper MOCK_METHOD(char, DoThis, (int n), (override)); 66328f6c2f2SEnji Cooper MOCK_METHOD(void, DoThat, (const char* s, int* p), (override)); 66428f6c2f2SEnji Cooper 66528f6c2f2SEnji Cooper // Delegates the default actions of the methods to a FakeFoo object. 66628f6c2f2SEnji Cooper // This must be called *before* the custom ON_CALL() statements. 66728f6c2f2SEnji Cooper void DelegateToFake() { 66828f6c2f2SEnji Cooper ON_CALL(*this, DoThis).WillByDefault([this](int n) { 66928f6c2f2SEnji Cooper return fake_.DoThis(n); 67028f6c2f2SEnji Cooper }); 67128f6c2f2SEnji Cooper ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) { 67228f6c2f2SEnji Cooper fake_.DoThat(s, p); 67328f6c2f2SEnji Cooper }); 67428f6c2f2SEnji Cooper } 67528f6c2f2SEnji Cooper 67628f6c2f2SEnji Cooper private: 67728f6c2f2SEnji Cooper FakeFoo fake_; // Keeps an instance of the fake in the mock. 67828f6c2f2SEnji Cooper}; 67928f6c2f2SEnji Cooper``` 68028f6c2f2SEnji Cooper 68128f6c2f2SEnji CooperWith that, you can use `MockFoo` in your tests as usual. Just remember that if 68228f6c2f2SEnji Cooperyou don't explicitly set an action in an `ON_CALL()` or `EXPECT_CALL()`, the 68328f6c2f2SEnji Cooperfake will be called upon to do it.: 68428f6c2f2SEnji Cooper 68528f6c2f2SEnji Cooper```cpp 68628f6c2f2SEnji Cooperusing ::testing::_; 68728f6c2f2SEnji Cooper 68828f6c2f2SEnji CooperTEST(AbcTest, Xyz) { 68928f6c2f2SEnji Cooper MockFoo foo; 69028f6c2f2SEnji Cooper 69128f6c2f2SEnji Cooper foo.DelegateToFake(); // Enables the fake for delegation. 69228f6c2f2SEnji Cooper 69328f6c2f2SEnji Cooper // Put your ON_CALL(foo, ...)s here, if any. 69428f6c2f2SEnji Cooper 69528f6c2f2SEnji Cooper // No action specified, meaning to use the default action. 69628f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(5)); 69728f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThat(_, _)); 69828f6c2f2SEnji Cooper 69928f6c2f2SEnji Cooper int n = 0; 70028f6c2f2SEnji Cooper EXPECT_EQ(foo.DoThis(5), '+'); // FakeFoo::DoThis() is invoked. 70128f6c2f2SEnji Cooper foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. 70228f6c2f2SEnji Cooper EXPECT_EQ(n, 2); 70328f6c2f2SEnji Cooper} 70428f6c2f2SEnji Cooper``` 70528f6c2f2SEnji Cooper 70628f6c2f2SEnji Cooper**Some tips:** 70728f6c2f2SEnji Cooper 70828f6c2f2SEnji Cooper* If you want, you can still override the default action by providing your own 70928f6c2f2SEnji Cooper `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. 71028f6c2f2SEnji Cooper* In `DelegateToFake()`, you only need to delegate the methods whose fake 71128f6c2f2SEnji Cooper implementation you intend to use. 71228f6c2f2SEnji Cooper 71328f6c2f2SEnji Cooper* The general technique discussed here works for overloaded methods, but 71428f6c2f2SEnji Cooper you'll need to tell the compiler which version you mean. To disambiguate a 71528f6c2f2SEnji Cooper mock function (the one you specify inside the parentheses of `ON_CALL()`), 71628f6c2f2SEnji Cooper use [this technique](#SelectOverload); to disambiguate a fake function (the 71728f6c2f2SEnji Cooper one you place inside `Invoke()`), use a `static_cast` to specify the 71828f6c2f2SEnji Cooper function's type. For instance, if class `Foo` has methods `char DoThis(int 71928f6c2f2SEnji Cooper n)` and `bool DoThis(double x) const`, and you want to invoke the latter, 72028f6c2f2SEnji Cooper you need to write `Invoke(&fake_, static_cast<bool (FakeFoo::*)(double) 72128f6c2f2SEnji Cooper const>(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` 72228f6c2f2SEnji Cooper (The strange-looking thing inside the angled brackets of `static_cast` is 72328f6c2f2SEnji Cooper the type of a function pointer to the second `DoThis()` method.). 72428f6c2f2SEnji Cooper 72528f6c2f2SEnji Cooper* Having to mix a mock and a fake is often a sign of something gone wrong. 72628f6c2f2SEnji Cooper Perhaps you haven't got used to the interaction-based way of testing yet. Or 72728f6c2f2SEnji Cooper perhaps your interface is taking on too many roles and should be split up. 72828f6c2f2SEnji Cooper Therefore, **don't abuse this**. We would only recommend to do it as an 72928f6c2f2SEnji Cooper intermediate step when you are refactoring your code. 73028f6c2f2SEnji Cooper 73128f6c2f2SEnji CooperRegarding the tip on mixing a mock and a fake, here's an example on why it may 73228f6c2f2SEnji Cooperbe a bad sign: Suppose you have a class `System` for low-level system 73328f6c2f2SEnji Cooperoperations. In particular, it does file and I/O operations. And suppose you want 73428f6c2f2SEnji Cooperto test how your code uses `System` to do I/O, and you just want the file 73528f6c2f2SEnji Cooperoperations to work normally. If you mock out the entire `System` class, you'll 73628f6c2f2SEnji Cooperhave to provide a fake implementation for the file operation part, which 73728f6c2f2SEnji Coopersuggests that `System` is taking on too many roles. 73828f6c2f2SEnji Cooper 73928f6c2f2SEnji CooperInstead, you can define a `FileOps` interface and an `IOOps` interface and split 74028f6c2f2SEnji Cooper`System`'s functionalities into the two. Then you can mock `IOOps` without 74128f6c2f2SEnji Coopermocking `FileOps`. 74228f6c2f2SEnji Cooper 74328f6c2f2SEnji Cooper### Delegating Calls to a Real Object 74428f6c2f2SEnji Cooper 74528f6c2f2SEnji CooperWhen using testing doubles (mocks, fakes, stubs, and etc), sometimes their 74628f6c2f2SEnji Cooperbehaviors will differ from those of the real objects. This difference could be 74728f6c2f2SEnji Coopereither intentional (as in simulating an error such that you can test the error 74828f6c2f2SEnji Cooperhandling code) or unintentional. If your mocks have different behaviors than the 74928f6c2f2SEnji Cooperreal objects by mistake, you could end up with code that passes the tests but 75028f6c2f2SEnji Cooperfails in production. 75128f6c2f2SEnji Cooper 75228f6c2f2SEnji CooperYou can use the *delegating-to-real* technique to ensure that your mock has the 75328f6c2f2SEnji Coopersame behavior as the real object while retaining the ability to validate calls. 75428f6c2f2SEnji CooperThis technique is very similar to the [delegating-to-fake](#DelegatingToFake) 75528f6c2f2SEnji Coopertechnique, the difference being that we use a real object instead of a fake. 75628f6c2f2SEnji CooperHere's an example: 75728f6c2f2SEnji Cooper 75828f6c2f2SEnji Cooper```cpp 75928f6c2f2SEnji Cooperusing ::testing::AtLeast; 76028f6c2f2SEnji Cooper 76128f6c2f2SEnji Cooperclass MockFoo : public Foo { 76228f6c2f2SEnji Cooper public: 76328f6c2f2SEnji Cooper MockFoo() { 76428f6c2f2SEnji Cooper // By default, all calls are delegated to the real object. 76528f6c2f2SEnji Cooper ON_CALL(*this, DoThis).WillByDefault([this](int n) { 76628f6c2f2SEnji Cooper return real_.DoThis(n); 76728f6c2f2SEnji Cooper }); 76828f6c2f2SEnji Cooper ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) { 76928f6c2f2SEnji Cooper real_.DoThat(s, p); 77028f6c2f2SEnji Cooper }); 77128f6c2f2SEnji Cooper ... 77228f6c2f2SEnji Cooper } 77328f6c2f2SEnji Cooper MOCK_METHOD(char, DoThis, ...); 77428f6c2f2SEnji Cooper MOCK_METHOD(void, DoThat, ...); 77528f6c2f2SEnji Cooper ... 77628f6c2f2SEnji Cooper private: 77728f6c2f2SEnji Cooper Foo real_; 77828f6c2f2SEnji Cooper}; 77928f6c2f2SEnji Cooper 78028f6c2f2SEnji Cooper... 78128f6c2f2SEnji Cooper MockFoo mock; 78228f6c2f2SEnji Cooper EXPECT_CALL(mock, DoThis()) 78328f6c2f2SEnji Cooper .Times(3); 78428f6c2f2SEnji Cooper EXPECT_CALL(mock, DoThat("Hi")) 78528f6c2f2SEnji Cooper .Times(AtLeast(1)); 78628f6c2f2SEnji Cooper ... use mock in test ... 78728f6c2f2SEnji Cooper``` 78828f6c2f2SEnji Cooper 78928f6c2f2SEnji CooperWith this, gMock will verify that your code made the right calls (with the right 79028f6c2f2SEnji Cooperarguments, in the right order, called the right number of times, etc), and a 79128f6c2f2SEnji Cooperreal object will answer the calls (so the behavior will be the same as in 79228f6c2f2SEnji Cooperproduction). This gives you the best of both worlds. 79328f6c2f2SEnji Cooper 79428f6c2f2SEnji Cooper### Delegating Calls to a Parent Class 79528f6c2f2SEnji Cooper 79628f6c2f2SEnji CooperIdeally, you should code to interfaces, whose methods are all pure virtual. In 79728f6c2f2SEnji Cooperreality, sometimes you do need to mock a virtual method that is not pure (i.e, 79828f6c2f2SEnji Cooperit already has an implementation). For example: 79928f6c2f2SEnji Cooper 80028f6c2f2SEnji Cooper```cpp 80128f6c2f2SEnji Cooperclass Foo { 80228f6c2f2SEnji Cooper public: 80328f6c2f2SEnji Cooper virtual ~Foo(); 80428f6c2f2SEnji Cooper 80528f6c2f2SEnji Cooper virtual void Pure(int n) = 0; 80628f6c2f2SEnji Cooper virtual int Concrete(const char* str) { ... } 80728f6c2f2SEnji Cooper}; 80828f6c2f2SEnji Cooper 80928f6c2f2SEnji Cooperclass MockFoo : public Foo { 81028f6c2f2SEnji Cooper public: 81128f6c2f2SEnji Cooper // Mocking a pure method. 81228f6c2f2SEnji Cooper MOCK_METHOD(void, Pure, (int n), (override)); 81328f6c2f2SEnji Cooper // Mocking a concrete method. Foo::Concrete() is shadowed. 81428f6c2f2SEnji Cooper MOCK_METHOD(int, Concrete, (const char* str), (override)); 81528f6c2f2SEnji Cooper}; 81628f6c2f2SEnji Cooper``` 81728f6c2f2SEnji Cooper 81828f6c2f2SEnji CooperSometimes you may want to call `Foo::Concrete()` instead of 81928f6c2f2SEnji Cooper`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub action, or 82028f6c2f2SEnji Cooperperhaps your test doesn't need to mock `Concrete()` at all (but it would be 82128f6c2f2SEnji Cooperoh-so painful to have to define a new mock class whenever you don't need to mock 82228f6c2f2SEnji Cooperone of its methods). 82328f6c2f2SEnji Cooper 82428f6c2f2SEnji CooperYou can call `Foo::Concrete()` inside an action by: 82528f6c2f2SEnji Cooper 82628f6c2f2SEnji Cooper```cpp 82728f6c2f2SEnji Cooper... 82828f6c2f2SEnji Cooper EXPECT_CALL(foo, Concrete).WillOnce([&foo](const char* str) { 82928f6c2f2SEnji Cooper return foo.Foo::Concrete(str); 83028f6c2f2SEnji Cooper }); 83128f6c2f2SEnji Cooper``` 83228f6c2f2SEnji Cooper 83328f6c2f2SEnji Cooperor tell the mock object that you don't want to mock `Concrete()`: 83428f6c2f2SEnji Cooper 83528f6c2f2SEnji Cooper```cpp 83628f6c2f2SEnji Cooper... 83728f6c2f2SEnji Cooper ON_CALL(foo, Concrete).WillByDefault([&foo](const char* str) { 83828f6c2f2SEnji Cooper return foo.Foo::Concrete(str); 83928f6c2f2SEnji Cooper }); 84028f6c2f2SEnji Cooper``` 84128f6c2f2SEnji Cooper 84228f6c2f2SEnji Cooper(Why don't we just write `{ return foo.Concrete(str); }`? If you do that, 84328f6c2f2SEnji Cooper`MockFoo::Concrete()` will be called (and cause an infinite recursion) since 84428f6c2f2SEnji Cooper`Foo::Concrete()` is virtual. That's just how C++ works.) 84528f6c2f2SEnji Cooper 84628f6c2f2SEnji Cooper## Using Matchers 84728f6c2f2SEnji Cooper 84828f6c2f2SEnji Cooper### Matching Argument Values Exactly 84928f6c2f2SEnji Cooper 85028f6c2f2SEnji CooperYou can specify exactly which arguments a mock method is expecting: 85128f6c2f2SEnji Cooper 85228f6c2f2SEnji Cooper```cpp 85328f6c2f2SEnji Cooperusing ::testing::Return; 85428f6c2f2SEnji Cooper... 85528f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(5)) 85628f6c2f2SEnji Cooper .WillOnce(Return('a')); 85728f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThat("Hello", bar)); 85828f6c2f2SEnji Cooper``` 85928f6c2f2SEnji Cooper 86028f6c2f2SEnji Cooper### Using Simple Matchers 86128f6c2f2SEnji Cooper 86228f6c2f2SEnji CooperYou can use matchers to match arguments that have a certain property: 86328f6c2f2SEnji Cooper 86428f6c2f2SEnji Cooper```cpp 86528f6c2f2SEnji Cooperusing ::testing::NotNull; 86628f6c2f2SEnji Cooperusing ::testing::Return; 86728f6c2f2SEnji Cooper... 86828f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. 86928f6c2f2SEnji Cooper .WillOnce(Return('a')); 87028f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThat("Hello", NotNull())); 87128f6c2f2SEnji Cooper // The second argument must not be NULL. 87228f6c2f2SEnji Cooper``` 87328f6c2f2SEnji Cooper 87428f6c2f2SEnji CooperA frequently used matcher is `_`, which matches anything: 87528f6c2f2SEnji Cooper 87628f6c2f2SEnji Cooper```cpp 87728f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThat(_, NotNull())); 87828f6c2f2SEnji Cooper``` 87928f6c2f2SEnji Cooper 88028f6c2f2SEnji Cooper### Combining Matchers {#CombiningMatchers} 88128f6c2f2SEnji Cooper 88228f6c2f2SEnji CooperYou can build complex matchers from existing ones using `AllOf()`, 88328f6c2f2SEnji Cooper`AllOfArray()`, `AnyOf()`, `AnyOfArray()` and `Not()`: 88428f6c2f2SEnji Cooper 88528f6c2f2SEnji Cooper```cpp 88628f6c2f2SEnji Cooperusing ::testing::AllOf; 88728f6c2f2SEnji Cooperusing ::testing::Gt; 88828f6c2f2SEnji Cooperusing ::testing::HasSubstr; 88928f6c2f2SEnji Cooperusing ::testing::Ne; 89028f6c2f2SEnji Cooperusing ::testing::Not; 89128f6c2f2SEnji Cooper... 89228f6c2f2SEnji Cooper // The argument must be > 5 and != 10. 89328f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(AllOf(Gt(5), 89428f6c2f2SEnji Cooper Ne(10)))); 89528f6c2f2SEnji Cooper 89628f6c2f2SEnji Cooper // The first argument must not contain sub-string "blah". 89728f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), 89828f6c2f2SEnji Cooper NULL)); 89928f6c2f2SEnji Cooper``` 90028f6c2f2SEnji Cooper 90128f6c2f2SEnji CooperMatchers are function objects, and parametrized matchers can be composed just 90228f6c2f2SEnji Cooperlike any other function. However because their types can be long and rarely 90328f6c2f2SEnji Cooperprovide meaningful information, it can be easier to express them with C++14 90428f6c2f2SEnji Coopergeneric lambdas to avoid specifying types. For example, 90528f6c2f2SEnji Cooper 90628f6c2f2SEnji Cooper```cpp 90728f6c2f2SEnji Cooperusing ::testing::Contains; 90828f6c2f2SEnji Cooperusing ::testing::Property; 90928f6c2f2SEnji Cooper 91028f6c2f2SEnji Cooperinline constexpr auto HasFoo = [](const auto& f) { 91128f6c2f2SEnji Cooper return Property("foo", &MyClass::foo, Contains(f)); 91228f6c2f2SEnji Cooper}; 91328f6c2f2SEnji Cooper... 91428f6c2f2SEnji Cooper EXPECT_THAT(x, HasFoo("blah")); 91528f6c2f2SEnji Cooper``` 91628f6c2f2SEnji Cooper 91728f6c2f2SEnji Cooper### Casting Matchers {#SafeMatcherCast} 91828f6c2f2SEnji Cooper 91928f6c2f2SEnji CoopergMock matchers are statically typed, meaning that the compiler can catch your 92028f6c2f2SEnji Coopermistake if you use a matcher of the wrong type (for example, if you use `Eq(5)` 92128f6c2f2SEnji Cooperto match a `string` argument). Good for you! 92228f6c2f2SEnji Cooper 92328f6c2f2SEnji CooperSometimes, however, you know what you're doing and want the compiler to give you 92428f6c2f2SEnji Coopersome slack. One example is that you have a matcher for `long` and the argument 92528f6c2f2SEnji Cooperyou want to match is `int`. While the two types aren't exactly the same, there 92628f6c2f2SEnji Cooperis nothing really wrong with using a `Matcher<long>` to match an `int` - after 92728f6c2f2SEnji Cooperall, we can first convert the `int` argument to a `long` losslessly before 92828f6c2f2SEnji Coopergiving it to the matcher. 92928f6c2f2SEnji Cooper 93028f6c2f2SEnji CooperTo support this need, gMock gives you the `SafeMatcherCast<T>(m)` function. It 93128f6c2f2SEnji Coopercasts a matcher `m` to type `Matcher<T>`. To ensure safety, gMock checks that 93228f6c2f2SEnji Cooper(let `U` be the type `m` accepts : 93328f6c2f2SEnji Cooper 93428f6c2f2SEnji Cooper1. Type `T` can be *implicitly* cast to type `U`; 93528f6c2f2SEnji Cooper2. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and 93628f6c2f2SEnji Cooper floating-point numbers), the conversion from `T` to `U` is not lossy (in 93728f6c2f2SEnji Cooper other words, any value representable by `T` can also be represented by `U`); 93828f6c2f2SEnji Cooper and 93928f6c2f2SEnji Cooper3. When `U` is a reference, `T` must also be a reference (as the underlying 94028f6c2f2SEnji Cooper matcher may be interested in the address of the `U` value). 94128f6c2f2SEnji Cooper 94228f6c2f2SEnji CooperThe code won't compile if any of these conditions isn't met. 94328f6c2f2SEnji Cooper 94428f6c2f2SEnji CooperHere's one example: 94528f6c2f2SEnji Cooper 94628f6c2f2SEnji Cooper```cpp 94728f6c2f2SEnji Cooperusing ::testing::SafeMatcherCast; 94828f6c2f2SEnji Cooper 94928f6c2f2SEnji Cooper// A base class and a child class. 95028f6c2f2SEnji Cooperclass Base { ... }; 95128f6c2f2SEnji Cooperclass Derived : public Base { ... }; 95228f6c2f2SEnji Cooper 95328f6c2f2SEnji Cooperclass MockFoo : public Foo { 95428f6c2f2SEnji Cooper public: 95528f6c2f2SEnji Cooper MOCK_METHOD(void, DoThis, (Derived* derived), (override)); 95628f6c2f2SEnji Cooper}; 95728f6c2f2SEnji Cooper 95828f6c2f2SEnji Cooper... 95928f6c2f2SEnji Cooper MockFoo foo; 96028f6c2f2SEnji Cooper // m is a Matcher<Base*> we got from somewhere. 96128f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m))); 96228f6c2f2SEnji Cooper``` 96328f6c2f2SEnji Cooper 96428f6c2f2SEnji CooperIf you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar function 96528f6c2f2SEnji Cooper`MatcherCast<T>(m)`. The difference is that `MatcherCast` works as long as you 96628f6c2f2SEnji Coopercan `static_cast` type `T` to type `U`. 96728f6c2f2SEnji Cooper 96828f6c2f2SEnji Cooper`MatcherCast` essentially lets you bypass C++'s type system (`static_cast` isn't 96928f6c2f2SEnji Cooperalways safe as it could throw away information, for example), so be careful not 97028f6c2f2SEnji Cooperto misuse/abuse it. 97128f6c2f2SEnji Cooper 97228f6c2f2SEnji Cooper### Selecting Between Overloaded Functions {#SelectOverload} 97328f6c2f2SEnji Cooper 97428f6c2f2SEnji CooperIf you expect an overloaded function to be called, the compiler may need some 97528f6c2f2SEnji Cooperhelp on which overloaded version it is. 97628f6c2f2SEnji Cooper 97728f6c2f2SEnji CooperTo disambiguate functions overloaded on the const-ness of this object, use the 97828f6c2f2SEnji Cooper`Const()` argument wrapper. 97928f6c2f2SEnji Cooper 98028f6c2f2SEnji Cooper```cpp 98128f6c2f2SEnji Cooperusing ::testing::ReturnRef; 98228f6c2f2SEnji Cooper 98328f6c2f2SEnji Cooperclass MockFoo : public Foo { 98428f6c2f2SEnji Cooper ... 98528f6c2f2SEnji Cooper MOCK_METHOD(Bar&, GetBar, (), (override)); 98628f6c2f2SEnji Cooper MOCK_METHOD(const Bar&, GetBar, (), (const, override)); 98728f6c2f2SEnji Cooper}; 98828f6c2f2SEnji Cooper 98928f6c2f2SEnji Cooper... 99028f6c2f2SEnji Cooper MockFoo foo; 99128f6c2f2SEnji Cooper Bar bar1, bar2; 99228f6c2f2SEnji Cooper EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). 99328f6c2f2SEnji Cooper .WillOnce(ReturnRef(bar1)); 99428f6c2f2SEnji Cooper EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). 99528f6c2f2SEnji Cooper .WillOnce(ReturnRef(bar2)); 99628f6c2f2SEnji Cooper``` 99728f6c2f2SEnji Cooper 99828f6c2f2SEnji Cooper(`Const()` is defined by gMock and returns a `const` reference to its argument.) 99928f6c2f2SEnji Cooper 100028f6c2f2SEnji CooperTo disambiguate overloaded functions with the same number of arguments but 100128f6c2f2SEnji Cooperdifferent argument types, you may need to specify the exact type of a matcher, 100228f6c2f2SEnji Coopereither by wrapping your matcher in `Matcher<type>()`, or using a matcher whose 100328f6c2f2SEnji Coopertype is fixed (`TypedEq<type>`, `An<type>()`, etc): 100428f6c2f2SEnji Cooper 100528f6c2f2SEnji Cooper```cpp 100628f6c2f2SEnji Cooperusing ::testing::An; 100728f6c2f2SEnji Cooperusing ::testing::Matcher; 100828f6c2f2SEnji Cooperusing ::testing::TypedEq; 100928f6c2f2SEnji Cooper 101028f6c2f2SEnji Cooperclass MockPrinter : public Printer { 101128f6c2f2SEnji Cooper public: 101228f6c2f2SEnji Cooper MOCK_METHOD(void, Print, (int n), (override)); 101328f6c2f2SEnji Cooper MOCK_METHOD(void, Print, (char c), (override)); 101428f6c2f2SEnji Cooper}; 101528f6c2f2SEnji Cooper 101628f6c2f2SEnji CooperTEST(PrinterTest, Print) { 101728f6c2f2SEnji Cooper MockPrinter printer; 101828f6c2f2SEnji Cooper 101928f6c2f2SEnji Cooper EXPECT_CALL(printer, Print(An<int>())); // void Print(int); 102028f6c2f2SEnji Cooper EXPECT_CALL(printer, Print(Matcher<int>(Lt(5)))); // void Print(int); 102128f6c2f2SEnji Cooper EXPECT_CALL(printer, Print(TypedEq<char>('a'))); // void Print(char); 102228f6c2f2SEnji Cooper 102328f6c2f2SEnji Cooper printer.Print(3); 102428f6c2f2SEnji Cooper printer.Print(6); 102528f6c2f2SEnji Cooper printer.Print('a'); 102628f6c2f2SEnji Cooper} 102728f6c2f2SEnji Cooper``` 102828f6c2f2SEnji Cooper 102928f6c2f2SEnji Cooper### Performing Different Actions Based on the Arguments 103028f6c2f2SEnji Cooper 103128f6c2f2SEnji CooperWhen a mock method is called, the *last* matching expectation that's still 103228f6c2f2SEnji Cooperactive will be selected (think "newer overrides older"). So, you can make a 103328f6c2f2SEnji Coopermethod do different things depending on its argument values like this: 103428f6c2f2SEnji Cooper 103528f6c2f2SEnji Cooper```cpp 103628f6c2f2SEnji Cooperusing ::testing::_; 103728f6c2f2SEnji Cooperusing ::testing::Lt; 103828f6c2f2SEnji Cooperusing ::testing::Return; 103928f6c2f2SEnji Cooper... 104028f6c2f2SEnji Cooper // The default case. 104128f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(_)) 104228f6c2f2SEnji Cooper .WillRepeatedly(Return('b')); 104328f6c2f2SEnji Cooper // The more specific case. 104428f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(Lt(5))) 104528f6c2f2SEnji Cooper .WillRepeatedly(Return('a')); 104628f6c2f2SEnji Cooper``` 104728f6c2f2SEnji Cooper 104828f6c2f2SEnji CooperNow, if `foo.DoThis()` is called with a value less than 5, `'a'` will be 104928f6c2f2SEnji Cooperreturned; otherwise `'b'` will be returned. 105028f6c2f2SEnji Cooper 105128f6c2f2SEnji Cooper### Matching Multiple Arguments as a Whole 105228f6c2f2SEnji Cooper 105328f6c2f2SEnji CooperSometimes it's not enough to match the arguments individually. For example, we 105428f6c2f2SEnji Coopermay want to say that the first argument must be less than the second argument. 105528f6c2f2SEnji CooperThe `With()` clause allows us to match all arguments of a mock function as a 105628f6c2f2SEnji Cooperwhole. For example, 105728f6c2f2SEnji Cooper 105828f6c2f2SEnji Cooper```cpp 105928f6c2f2SEnji Cooperusing ::testing::_; 106028f6c2f2SEnji Cooperusing ::testing::Ne; 106128f6c2f2SEnji Cooperusing ::testing::Lt; 106228f6c2f2SEnji Cooper... 106328f6c2f2SEnji Cooper EXPECT_CALL(foo, InRange(Ne(0), _)) 106428f6c2f2SEnji Cooper .With(Lt()); 106528f6c2f2SEnji Cooper``` 106628f6c2f2SEnji Cooper 106728f6c2f2SEnji Coopersays that the first argument of `InRange()` must not be 0, and must be less than 106828f6c2f2SEnji Cooperthe second argument. 106928f6c2f2SEnji Cooper 107028f6c2f2SEnji CooperThe expression inside `With()` must be a matcher of type `Matcher<std::tuple<A1, 107128f6c2f2SEnji Cooper..., An>>`, where `A1`, ..., `An` are the types of the function arguments. 107228f6c2f2SEnji Cooper 107328f6c2f2SEnji CooperYou can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms 107428f6c2f2SEnji Cooperare equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`. 107528f6c2f2SEnji Cooper 107628f6c2f2SEnji CooperYou can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments (as a 107728f6c2f2SEnji Coopertuple) against `m`. For example, 107828f6c2f2SEnji Cooper 107928f6c2f2SEnji Cooper```cpp 108028f6c2f2SEnji Cooperusing ::testing::_; 108128f6c2f2SEnji Cooperusing ::testing::AllOf; 108228f6c2f2SEnji Cooperusing ::testing::Args; 108328f6c2f2SEnji Cooperusing ::testing::Lt; 108428f6c2f2SEnji Cooper... 108528f6c2f2SEnji Cooper EXPECT_CALL(foo, Blah) 108628f6c2f2SEnji Cooper .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); 108728f6c2f2SEnji Cooper``` 108828f6c2f2SEnji Cooper 108928f6c2f2SEnji Coopersays that `Blah` will be called with arguments `x`, `y`, and `z` where `x < y < 109028f6c2f2SEnji Cooperz`. Note that in this example, it wasn't necessary to specify the positional 109128f6c2f2SEnji Coopermatchers. 109228f6c2f2SEnji Cooper 109328f6c2f2SEnji CooperAs a convenience and example, gMock provides some matchers for 2-tuples, 109428f6c2f2SEnji Cooperincluding the `Lt()` matcher above. See 109528f6c2f2SEnji Cooper[Multi-argument Matchers](reference/matchers.md#MultiArgMatchers) for the 109628f6c2f2SEnji Coopercomplete list. 109728f6c2f2SEnji Cooper 109828f6c2f2SEnji CooperNote that if you want to pass the arguments to a predicate of your own (e.g. 109928f6c2f2SEnji Cooper`.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to 110028f6c2f2SEnji Coopertake a `std::tuple` as its argument; gMock will pass the `n` selected arguments 110128f6c2f2SEnji Cooperas *one* single tuple to the predicate. 110228f6c2f2SEnji Cooper 110328f6c2f2SEnji Cooper### Using Matchers as Predicates 110428f6c2f2SEnji Cooper 110528f6c2f2SEnji CooperHave you noticed that a matcher is just a fancy predicate that also knows how to 110628f6c2f2SEnji Cooperdescribe itself? Many existing algorithms take predicates as arguments (e.g. 110728f6c2f2SEnji Cooperthose defined in STL's `<algorithm>` header), and it would be a shame if gMock 110828f6c2f2SEnji Coopermatchers were not allowed to participate. 110928f6c2f2SEnji Cooper 111028f6c2f2SEnji CooperLuckily, you can use a matcher where a unary predicate functor is expected by 111128f6c2f2SEnji Cooperwrapping it inside the `Matches()` function. For example, 111228f6c2f2SEnji Cooper 111328f6c2f2SEnji Cooper```cpp 111428f6c2f2SEnji Cooper#include <algorithm> 111528f6c2f2SEnji Cooper#include <vector> 111628f6c2f2SEnji Cooper 111728f6c2f2SEnji Cooperusing ::testing::Matches; 111828f6c2f2SEnji Cooperusing ::testing::Ge; 111928f6c2f2SEnji Cooper 112028f6c2f2SEnji Coopervector<int> v; 112128f6c2f2SEnji Cooper... 112228f6c2f2SEnji Cooper// How many elements in v are >= 10? 112328f6c2f2SEnji Cooperconst int count = count_if(v.begin(), v.end(), Matches(Ge(10))); 112428f6c2f2SEnji Cooper``` 112528f6c2f2SEnji Cooper 112628f6c2f2SEnji CooperSince you can build complex matchers from simpler ones easily using gMock, this 112728f6c2f2SEnji Coopergives you a way to conveniently construct composite predicates (doing the same 112828f6c2f2SEnji Cooperusing STL's `<functional>` header is just painful). For example, here's a 112928f6c2f2SEnji Cooperpredicate that's satisfied by any number that is >= 0, <= 100, and != 50: 113028f6c2f2SEnji Cooper 113128f6c2f2SEnji Cooper```cpp 113228f6c2f2SEnji Cooperusing ::testing::AllOf; 113328f6c2f2SEnji Cooperusing ::testing::Ge; 113428f6c2f2SEnji Cooperusing ::testing::Le; 113528f6c2f2SEnji Cooperusing ::testing::Matches; 113628f6c2f2SEnji Cooperusing ::testing::Ne; 113728f6c2f2SEnji Cooper... 113828f6c2f2SEnji CooperMatches(AllOf(Ge(0), Le(100), Ne(50))) 113928f6c2f2SEnji Cooper``` 114028f6c2f2SEnji Cooper 114128f6c2f2SEnji Cooper### Using Matchers in googletest Assertions 114228f6c2f2SEnji Cooper 114328f6c2f2SEnji CooperSee [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions 114428f6c2f2SEnji CooperReference. 114528f6c2f2SEnji Cooper 114628f6c2f2SEnji Cooper### Using Predicates as Matchers 114728f6c2f2SEnji Cooper 114828f6c2f2SEnji CoopergMock provides a set of built-in matchers for matching arguments with expected 114928f6c2f2SEnji Coopervalues—see the [Matchers Reference](reference/matchers.md) for more information. 115028f6c2f2SEnji CooperIn case you find the built-in set lacking, you can use an arbitrary unary 115128f6c2f2SEnji Cooperpredicate function or functor as a matcher - as long as the predicate accepts a 115228f6c2f2SEnji Coopervalue of the type you want. You do this by wrapping the predicate inside the 115328f6c2f2SEnji Cooper`Truly()` function, for example: 115428f6c2f2SEnji Cooper 115528f6c2f2SEnji Cooper```cpp 115628f6c2f2SEnji Cooperusing ::testing::Truly; 115728f6c2f2SEnji Cooper 115828f6c2f2SEnji Cooperint IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } 115928f6c2f2SEnji Cooper... 116028f6c2f2SEnji Cooper // Bar() must be called with an even number. 116128f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar(Truly(IsEven))); 116228f6c2f2SEnji Cooper``` 116328f6c2f2SEnji Cooper 116428f6c2f2SEnji CooperNote that the predicate function / functor doesn't have to return `bool`. It 116528f6c2f2SEnji Cooperworks as long as the return value can be used as the condition in the statement 116628f6c2f2SEnji Cooper`if (condition) ...`. 116728f6c2f2SEnji Cooper 116828f6c2f2SEnji Cooper### Matching Arguments that Are Not Copyable 116928f6c2f2SEnji Cooper 117028f6c2f2SEnji CooperWhen you do an `EXPECT_CALL(mock_obj, Foo(bar))`, gMock saves away a copy of 117128f6c2f2SEnji Cooper`bar`. When `Foo()` is called later, gMock compares the argument to `Foo()` with 117228f6c2f2SEnji Cooperthe saved copy of `bar`. This way, you don't need to worry about `bar` being 117328f6c2f2SEnji Coopermodified or destroyed after the `EXPECT_CALL()` is executed. The same is true 117428f6c2f2SEnji Cooperwhen you use matchers like `Eq(bar)`, `Le(bar)`, and so on. 117528f6c2f2SEnji Cooper 117628f6c2f2SEnji CooperBut what if `bar` cannot be copied (i.e. has no copy constructor)? You could 117728f6c2f2SEnji Cooperdefine your own matcher function or callback and use it with `Truly()`, as the 117828f6c2f2SEnji Cooperprevious couple of recipes have shown. Or, you may be able to get away from it 117928f6c2f2SEnji Cooperif you can guarantee that `bar` won't be changed after the `EXPECT_CALL()` is 118028f6c2f2SEnji Cooperexecuted. Just tell gMock that it should save a reference to `bar`, instead of a 118128f6c2f2SEnji Coopercopy of it. Here's how: 118228f6c2f2SEnji Cooper 118328f6c2f2SEnji Cooper```cpp 118428f6c2f2SEnji Cooperusing ::testing::Eq; 118528f6c2f2SEnji Cooperusing ::testing::Lt; 118628f6c2f2SEnji Cooper... 118728f6c2f2SEnji Cooper // Expects that Foo()'s argument == bar. 118828f6c2f2SEnji Cooper EXPECT_CALL(mock_obj, Foo(Eq(std::ref(bar)))); 118928f6c2f2SEnji Cooper 119028f6c2f2SEnji Cooper // Expects that Foo()'s argument < bar. 119128f6c2f2SEnji Cooper EXPECT_CALL(mock_obj, Foo(Lt(std::ref(bar)))); 119228f6c2f2SEnji Cooper``` 119328f6c2f2SEnji Cooper 119428f6c2f2SEnji CooperRemember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the 119528f6c2f2SEnji Cooperresult is undefined. 119628f6c2f2SEnji Cooper 119728f6c2f2SEnji Cooper### Validating a Member of an Object 119828f6c2f2SEnji Cooper 119928f6c2f2SEnji CooperOften a mock function takes a reference to object as an argument. When matching 120028f6c2f2SEnji Cooperthe argument, you may not want to compare the entire object against a fixed 120128f6c2f2SEnji Cooperobject, as that may be over-specification. Instead, you may need to validate a 120228f6c2f2SEnji Coopercertain member variable or the result of a certain getter method of the object. 120328f6c2f2SEnji CooperYou can do this with `Field()` and `Property()`. More specifically, 120428f6c2f2SEnji Cooper 120528f6c2f2SEnji Cooper```cpp 120628f6c2f2SEnji CooperField(&Foo::bar, m) 120728f6c2f2SEnji Cooper``` 120828f6c2f2SEnji Cooper 120928f6c2f2SEnji Cooperis a matcher that matches a `Foo` object whose `bar` member variable satisfies 121028f6c2f2SEnji Coopermatcher `m`. 121128f6c2f2SEnji Cooper 121228f6c2f2SEnji Cooper```cpp 121328f6c2f2SEnji CooperProperty(&Foo::baz, m) 121428f6c2f2SEnji Cooper``` 121528f6c2f2SEnji Cooper 121628f6c2f2SEnji Cooperis a matcher that matches a `Foo` object whose `baz()` method returns a value 121728f6c2f2SEnji Cooperthat satisfies matcher `m`. 121828f6c2f2SEnji Cooper 121928f6c2f2SEnji CooperFor example: 122028f6c2f2SEnji Cooper 122128f6c2f2SEnji Cooper| Expression | Description | 122228f6c2f2SEnji Cooper| :--------------------------- | :--------------------------------------- | 122328f6c2f2SEnji Cooper| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | 122428f6c2f2SEnji Cooper| `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | 122528f6c2f2SEnji Cooper 122628f6c2f2SEnji CooperNote that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument 122728f6c2f2SEnji Cooperand be declared as `const`. Don't use `Property()` against member functions that 122828f6c2f2SEnji Cooperyou do not own, because taking addresses of functions is fragile and generally 122928f6c2f2SEnji Coopernot part of the contract of the function. 123028f6c2f2SEnji Cooper 123128f6c2f2SEnji Cooper`Field()` and `Property()` can also match plain pointers to objects. For 123228f6c2f2SEnji Cooperinstance, 123328f6c2f2SEnji Cooper 123428f6c2f2SEnji Cooper```cpp 123528f6c2f2SEnji Cooperusing ::testing::Field; 123628f6c2f2SEnji Cooperusing ::testing::Ge; 123728f6c2f2SEnji Cooper... 123828f6c2f2SEnji CooperField(&Foo::number, Ge(3)) 123928f6c2f2SEnji Cooper``` 124028f6c2f2SEnji Cooper 124128f6c2f2SEnji Coopermatches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, the match 124228f6c2f2SEnji Cooperwill always fail regardless of the inner matcher. 124328f6c2f2SEnji Cooper 124428f6c2f2SEnji CooperWhat if you want to validate more than one members at the same time? Remember 124528f6c2f2SEnji Cooperthat there are [`AllOf()` and `AllOfArray()`](#CombiningMatchers). 124628f6c2f2SEnji Cooper 124728f6c2f2SEnji CooperFinally `Field()` and `Property()` provide overloads that take the field or 124828f6c2f2SEnji Cooperproperty names as the first argument to include it in the error message. This 124928f6c2f2SEnji Coopercan be useful when creating combined matchers. 125028f6c2f2SEnji Cooper 125128f6c2f2SEnji Cooper```cpp 125228f6c2f2SEnji Cooperusing ::testing::AllOf; 125328f6c2f2SEnji Cooperusing ::testing::Field; 125428f6c2f2SEnji Cooperusing ::testing::Matcher; 125528f6c2f2SEnji Cooperusing ::testing::SafeMatcherCast; 125628f6c2f2SEnji Cooper 125728f6c2f2SEnji CooperMatcher<Foo> IsFoo(const Foo& foo) { 125828f6c2f2SEnji Cooper return AllOf(Field("some_field", &Foo::some_field, foo.some_field), 125928f6c2f2SEnji Cooper Field("other_field", &Foo::other_field, foo.other_field), 126028f6c2f2SEnji Cooper Field("last_field", &Foo::last_field, foo.last_field)); 126128f6c2f2SEnji Cooper} 126228f6c2f2SEnji Cooper``` 126328f6c2f2SEnji Cooper 126428f6c2f2SEnji Cooper### Validating the Value Pointed to by a Pointer Argument 126528f6c2f2SEnji Cooper 126628f6c2f2SEnji CooperC++ functions often take pointers as arguments. You can use matchers like 126728f6c2f2SEnji Cooper`IsNull()`, `NotNull()`, and other comparison matchers to match a pointer, but 126828f6c2f2SEnji Cooperwhat if you want to make sure the value *pointed to* by the pointer, instead of 126928f6c2f2SEnji Cooperthe pointer itself, has a certain property? Well, you can use the `Pointee(m)` 127028f6c2f2SEnji Coopermatcher. 127128f6c2f2SEnji Cooper 127228f6c2f2SEnji Cooper`Pointee(m)` matches a pointer if and only if `m` matches the value the pointer 127328f6c2f2SEnji Cooperpoints to. For example: 127428f6c2f2SEnji Cooper 127528f6c2f2SEnji Cooper```cpp 127628f6c2f2SEnji Cooperusing ::testing::Ge; 127728f6c2f2SEnji Cooperusing ::testing::Pointee; 127828f6c2f2SEnji Cooper... 127928f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); 128028f6c2f2SEnji Cooper``` 128128f6c2f2SEnji Cooper 128228f6c2f2SEnji Cooperexpects `foo.Bar()` to be called with a pointer that points to a value greater 128328f6c2f2SEnji Cooperthan or equal to 3. 128428f6c2f2SEnji Cooper 128528f6c2f2SEnji CooperOne nice thing about `Pointee()` is that it treats a `NULL` pointer as a match 128628f6c2f2SEnji Cooperfailure, so you can write `Pointee(m)` instead of 128728f6c2f2SEnji Cooper 128828f6c2f2SEnji Cooper```cpp 128928f6c2f2SEnji Cooperusing ::testing::AllOf; 129028f6c2f2SEnji Cooperusing ::testing::NotNull; 129128f6c2f2SEnji Cooperusing ::testing::Pointee; 129228f6c2f2SEnji Cooper... 129328f6c2f2SEnji Cooper AllOf(NotNull(), Pointee(m)) 129428f6c2f2SEnji Cooper``` 129528f6c2f2SEnji Cooper 129628f6c2f2SEnji Cooperwithout worrying that a `NULL` pointer will crash your test. 129728f6c2f2SEnji Cooper 129828f6c2f2SEnji CooperAlso, did we tell you that `Pointee()` works with both raw pointers **and** 129928f6c2f2SEnji Coopersmart pointers (`std::unique_ptr`, `std::shared_ptr`, etc)? 130028f6c2f2SEnji Cooper 130128f6c2f2SEnji CooperWhat if you have a pointer to pointer? You guessed it - you can use nested 130228f6c2f2SEnji Cooper`Pointee()` to probe deeper inside the value. For example, 130328f6c2f2SEnji Cooper`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points 130428f6c2f2SEnji Cooperto a number less than 3 (what a mouthful...). 130528f6c2f2SEnji Cooper 130628f6c2f2SEnji Cooper### Defining a Custom Matcher Class {#CustomMatcherClass} 130728f6c2f2SEnji Cooper 130828f6c2f2SEnji CooperMost matchers can be simply defined using [the MATCHER* macros](#NewMatchers), 130928f6c2f2SEnji Cooperwhich are terse and flexible, and produce good error messages. However, these 131028f6c2f2SEnji Coopermacros are not very explicit about the interfaces they create and are not always 131128f6c2f2SEnji Coopersuitable, especially for matchers that will be widely reused. 131228f6c2f2SEnji Cooper 131328f6c2f2SEnji CooperFor more advanced cases, you may need to define your own matcher class. A custom 131428f6c2f2SEnji Coopermatcher allows you to test a specific invariant property of that object. Let's 131528f6c2f2SEnji Coopertake a look at how to do so. 131628f6c2f2SEnji Cooper 131728f6c2f2SEnji CooperImagine you have a mock function that takes an object of type `Foo`, which has 131828f6c2f2SEnji Cooperan `int bar()` method and an `int baz()` method. You want to constrain that the 131928f6c2f2SEnji Cooperargument's `bar()` value plus its `baz()` value is a given number. (This is an 132028f6c2f2SEnji Cooperinvariant.) Here's how we can write and use a matcher class to do so: 132128f6c2f2SEnji Cooper 132228f6c2f2SEnji Cooper```cpp 132328f6c2f2SEnji Cooperclass BarPlusBazEqMatcher { 132428f6c2f2SEnji Cooper public: 132528f6c2f2SEnji Cooper using is_gtest_matcher = void; 132628f6c2f2SEnji Cooper 132728f6c2f2SEnji Cooper explicit BarPlusBazEqMatcher(int expected_sum) 132828f6c2f2SEnji Cooper : expected_sum_(expected_sum) {} 132928f6c2f2SEnji Cooper 133028f6c2f2SEnji Cooper bool MatchAndExplain(const Foo& foo, 133128f6c2f2SEnji Cooper std::ostream* /* listener */) const { 133228f6c2f2SEnji Cooper return (foo.bar() + foo.baz()) == expected_sum_; 133328f6c2f2SEnji Cooper } 133428f6c2f2SEnji Cooper 133528f6c2f2SEnji Cooper void DescribeTo(std::ostream* os) const { 133628f6c2f2SEnji Cooper *os << "bar() + baz() equals " << expected_sum_; 133728f6c2f2SEnji Cooper } 133828f6c2f2SEnji Cooper 133928f6c2f2SEnji Cooper void DescribeNegationTo(std::ostream* os) const { 134028f6c2f2SEnji Cooper *os << "bar() + baz() does not equal " << expected_sum_; 134128f6c2f2SEnji Cooper } 134228f6c2f2SEnji Cooper private: 134328f6c2f2SEnji Cooper const int expected_sum_; 134428f6c2f2SEnji Cooper}; 134528f6c2f2SEnji Cooper 134628f6c2f2SEnji Cooper::testing::Matcher<const Foo&> BarPlusBazEq(int expected_sum) { 134728f6c2f2SEnji Cooper return BarPlusBazEqMatcher(expected_sum); 134828f6c2f2SEnji Cooper} 134928f6c2f2SEnji Cooper 135028f6c2f2SEnji Cooper... 135128f6c2f2SEnji Cooper Foo foo; 135228f6c2f2SEnji Cooper EXPECT_THAT(foo, BarPlusBazEq(5))...; 135328f6c2f2SEnji Cooper``` 135428f6c2f2SEnji Cooper 135528f6c2f2SEnji Cooper### Matching Containers 135628f6c2f2SEnji Cooper 135728f6c2f2SEnji CooperSometimes an STL container (e.g. list, vector, map, ...) is passed to a mock 135828f6c2f2SEnji Cooperfunction and you may want to validate it. Since most STL containers support the 135928f6c2f2SEnji Cooper`==` operator, you can write `Eq(expected_container)` or simply 136028f6c2f2SEnji Cooper`expected_container` to match a container exactly. 136128f6c2f2SEnji Cooper 136228f6c2f2SEnji CooperSometimes, though, you may want to be more flexible (for example, the first 136328f6c2f2SEnji Cooperelement must be an exact match, but the second element can be any positive 136428f6c2f2SEnji Coopernumber, and so on). Also, containers used in tests often have a small number of 136528f6c2f2SEnji Cooperelements, and having to define the expected container out-of-line is a bit of a 136628f6c2f2SEnji Cooperhassle. 136728f6c2f2SEnji Cooper 136828f6c2f2SEnji CooperYou can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in such 136928f6c2f2SEnji Coopercases: 137028f6c2f2SEnji Cooper 137128f6c2f2SEnji Cooper```cpp 137228f6c2f2SEnji Cooperusing ::testing::_; 137328f6c2f2SEnji Cooperusing ::testing::ElementsAre; 137428f6c2f2SEnji Cooperusing ::testing::Gt; 137528f6c2f2SEnji Cooper... 137628f6c2f2SEnji Cooper MOCK_METHOD(void, Foo, (const vector<int>& numbers), (override)); 137728f6c2f2SEnji Cooper... 137828f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); 137928f6c2f2SEnji Cooper``` 138028f6c2f2SEnji Cooper 138128f6c2f2SEnji CooperThe above matcher says that the container must have 4 elements, which must be 1, 138228f6c2f2SEnji Coopergreater than 0, anything, and 5 respectively. 138328f6c2f2SEnji Cooper 138428f6c2f2SEnji CooperIf you instead write: 138528f6c2f2SEnji Cooper 138628f6c2f2SEnji Cooper```cpp 138728f6c2f2SEnji Cooperusing ::testing::_; 138828f6c2f2SEnji Cooperusing ::testing::Gt; 138928f6c2f2SEnji Cooperusing ::testing::UnorderedElementsAre; 139028f6c2f2SEnji Cooper... 139128f6c2f2SEnji Cooper MOCK_METHOD(void, Foo, (const vector<int>& numbers), (override)); 139228f6c2f2SEnji Cooper... 139328f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5))); 139428f6c2f2SEnji Cooper``` 139528f6c2f2SEnji Cooper 139628f6c2f2SEnji CooperIt means that the container must have 4 elements, which (under some permutation) 139728f6c2f2SEnji Coopermust be 1, greater than 0, anything, and 5 respectively. 139828f6c2f2SEnji Cooper 139928f6c2f2SEnji CooperAs an alternative you can place the arguments in a C-style array and use 140028f6c2f2SEnji Cooper`ElementsAreArray()` or `UnorderedElementsAreArray()` instead: 140128f6c2f2SEnji Cooper 140228f6c2f2SEnji Cooper```cpp 140328f6c2f2SEnji Cooperusing ::testing::ElementsAreArray; 140428f6c2f2SEnji Cooper... 140528f6c2f2SEnji Cooper // ElementsAreArray accepts an array of element values. 140628f6c2f2SEnji Cooper const int expected_vector1[] = {1, 5, 2, 4, ...}; 140728f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); 140828f6c2f2SEnji Cooper 140928f6c2f2SEnji Cooper // Or, an array of element matchers. 141028f6c2f2SEnji Cooper Matcher<int> expected_vector2[] = {1, Gt(2), _, 3, ...}; 141128f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); 141228f6c2f2SEnji Cooper``` 141328f6c2f2SEnji Cooper 141428f6c2f2SEnji CooperIn case the array needs to be dynamically created (and therefore the array size 141528f6c2f2SEnji Coopercannot be inferred by the compiler), you can give `ElementsAreArray()` an 141628f6c2f2SEnji Cooperadditional argument to specify the array size: 141728f6c2f2SEnji Cooper 141828f6c2f2SEnji Cooper```cpp 141928f6c2f2SEnji Cooperusing ::testing::ElementsAreArray; 142028f6c2f2SEnji Cooper... 142128f6c2f2SEnji Cooper int* const expected_vector3 = new int[count]; 142228f6c2f2SEnji Cooper ... fill expected_vector3 with values ... 142328f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); 142428f6c2f2SEnji Cooper``` 142528f6c2f2SEnji Cooper 142628f6c2f2SEnji CooperUse `Pair` when comparing maps or other associative containers. 142728f6c2f2SEnji Cooper 142828f6c2f2SEnji Cooper{% raw %} 142928f6c2f2SEnji Cooper 143028f6c2f2SEnji Cooper```cpp 143128f6c2f2SEnji Cooperusing ::testing::UnorderedElementsAre; 143228f6c2f2SEnji Cooperusing ::testing::Pair; 143328f6c2f2SEnji Cooper... 143428f6c2f2SEnji Cooper absl::flat_hash_map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}}; 143528f6c2f2SEnji Cooper EXPECT_THAT(m, UnorderedElementsAre( 143628f6c2f2SEnji Cooper Pair("a", 1), Pair("b", 2), Pair("c", 3))); 143728f6c2f2SEnji Cooper``` 143828f6c2f2SEnji Cooper 143928f6c2f2SEnji Cooper{% endraw %} 144028f6c2f2SEnji Cooper 144128f6c2f2SEnji Cooper**Tips:** 144228f6c2f2SEnji Cooper 144328f6c2f2SEnji Cooper* `ElementsAre*()` can be used to match *any* container that implements the 144428f6c2f2SEnji Cooper STL iterator pattern (i.e. it has a `const_iterator` type and supports 144528f6c2f2SEnji Cooper `begin()/end()`), not just the ones defined in STL. It will even work with 144628f6c2f2SEnji Cooper container types yet to be written - as long as they follows the above 144728f6c2f2SEnji Cooper pattern. 144828f6c2f2SEnji Cooper* You can use nested `ElementsAre*()` to match nested (multi-dimensional) 144928f6c2f2SEnji Cooper containers. 145028f6c2f2SEnji Cooper* If the container is passed by pointer instead of by reference, just write 145128f6c2f2SEnji Cooper `Pointee(ElementsAre*(...))`. 145228f6c2f2SEnji Cooper* The order of elements *matters* for `ElementsAre*()`. If you are using it 145328f6c2f2SEnji Cooper with containers whose element order are undefined (such as a 145428f6c2f2SEnji Cooper `std::unordered_map`) you should use `UnorderedElementsAre`. 145528f6c2f2SEnji Cooper 145628f6c2f2SEnji Cooper### Sharing Matchers 145728f6c2f2SEnji Cooper 145828f6c2f2SEnji CooperUnder the hood, a gMock matcher object consists of a pointer to a ref-counted 145928f6c2f2SEnji Cooperimplementation object. Copying matchers is allowed and very efficient, as only 146028f6c2f2SEnji Cooperthe pointer is copied. When the last matcher that references the implementation 146128f6c2f2SEnji Cooperobject dies, the implementation object will be deleted. 146228f6c2f2SEnji Cooper 146328f6c2f2SEnji CooperTherefore, if you have some complex matcher that you want to use again and 146428f6c2f2SEnji Cooperagain, there is no need to build it every time. Just assign it to a matcher 146528f6c2f2SEnji Coopervariable and use that variable repeatedly! For example, 146628f6c2f2SEnji Cooper 146728f6c2f2SEnji Cooper```cpp 146828f6c2f2SEnji Cooperusing ::testing::AllOf; 146928f6c2f2SEnji Cooperusing ::testing::Gt; 147028f6c2f2SEnji Cooperusing ::testing::Le; 147128f6c2f2SEnji Cooperusing ::testing::Matcher; 147228f6c2f2SEnji Cooper... 147328f6c2f2SEnji Cooper Matcher<int> in_range = AllOf(Gt(5), Le(10)); 147428f6c2f2SEnji Cooper ... use in_range as a matcher in multiple EXPECT_CALLs ... 147528f6c2f2SEnji Cooper``` 147628f6c2f2SEnji Cooper 147728f6c2f2SEnji Cooper### Matchers must have no side-effects {#PureMatchers} 147828f6c2f2SEnji Cooper 147928f6c2f2SEnji Cooper{: .callout .warning} 148028f6c2f2SEnji CooperWARNING: gMock does not guarantee when or how many times a matcher will be 148128f6c2f2SEnji Cooperinvoked. Therefore, all matchers must be *purely functional*: they cannot have 148228f6c2f2SEnji Cooperany side effects, and the match result must not depend on anything other than 148328f6c2f2SEnji Cooperthe matcher's parameters and the value being matched. 148428f6c2f2SEnji Cooper 148528f6c2f2SEnji CooperThis requirement must be satisfied no matter how a matcher is defined (e.g., if 148628f6c2f2SEnji Cooperit is one of the standard matchers, or a custom matcher). In particular, a 148728f6c2f2SEnji Coopermatcher can never call a mock function, as that will affect the state of the 148828f6c2f2SEnji Coopermock object and gMock. 148928f6c2f2SEnji Cooper 149028f6c2f2SEnji Cooper## Setting Expectations 149128f6c2f2SEnji Cooper 149228f6c2f2SEnji Cooper### Knowing When to Expect {#UseOnCall} 149328f6c2f2SEnji Cooper 149428f6c2f2SEnji Cooper**`ON_CALL`** is likely the *single most under-utilized construct* in gMock. 149528f6c2f2SEnji Cooper 149628f6c2f2SEnji CooperThere are basically two constructs for defining the behavior of a mock object: 149728f6c2f2SEnji Cooper`ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when 149828f6c2f2SEnji Coopera mock method is called, but <em>doesn't imply any expectation on the method 149928f6c2f2SEnji Cooperbeing called</em>. `EXPECT_CALL` not only defines the behavior, but also sets an 150028f6c2f2SEnji Cooperexpectation that <em>the method will be called with the given arguments, for the 150128f6c2f2SEnji Coopergiven number of times</em> (and *in the given order* when you specify the order 150228f6c2f2SEnji Coopertoo). 150328f6c2f2SEnji Cooper 150428f6c2f2SEnji CooperSince `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every 150528f6c2f2SEnji Cooper`EXPECT_CALL` adds a constraint on the behavior of the code under test. Having 150628f6c2f2SEnji Coopermore constraints than necessary is *baaad* - even worse than not having enough 150728f6c2f2SEnji Cooperconstraints. 150828f6c2f2SEnji Cooper 150928f6c2f2SEnji CooperThis may be counter-intuitive. How could tests that verify more be worse than 151028f6c2f2SEnji Coopertests that verify less? Isn't verification the whole point of tests? 151128f6c2f2SEnji Cooper 151228f6c2f2SEnji CooperThe answer lies in *what* a test should verify. **A good test verifies the 151328f6c2f2SEnji Coopercontract of the code.** If a test over-specifies, it doesn't leave enough 151428f6c2f2SEnji Cooperfreedom to the implementation. As a result, changing the implementation without 151528f6c2f2SEnji Cooperbreaking the contract (e.g. refactoring and optimization), which should be 151628f6c2f2SEnji Cooperperfectly fine to do, can break such tests. Then you have to spend time fixing 151728f6c2f2SEnji Cooperthem, only to see them broken again the next time the implementation is changed. 151828f6c2f2SEnji Cooper 151928f6c2f2SEnji CooperKeep in mind that one doesn't have to verify more than one property in one test. 152028f6c2f2SEnji CooperIn fact, **it's a good style to verify only one thing in one test.** If you do 152128f6c2f2SEnji Cooperthat, a bug will likely break only one or two tests instead of dozens (which 152228f6c2f2SEnji Coopercase would you rather debug?). If you are also in the habit of giving tests 152328f6c2f2SEnji Cooperdescriptive names that tell what they verify, you can often easily guess what's 152428f6c2f2SEnji Cooperwrong just from the test log itself. 152528f6c2f2SEnji Cooper 152628f6c2f2SEnji CooperSo use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend 152728f6c2f2SEnji Cooperto verify that the call is made. For example, you may have a bunch of `ON_CALL`s 152828f6c2f2SEnji Cooperin your test fixture to set the common mock behavior shared by all tests in the 152928f6c2f2SEnji Coopersame group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s 153028f6c2f2SEnji Cooperto verify different aspects of the code's behavior. Compared with the style 153128f6c2f2SEnji Cooperwhere each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more 153228f6c2f2SEnji Cooperresilient to implementational changes (and thus less likely to require 153328f6c2f2SEnji Coopermaintenance) and makes the intent of the tests more obvious (so they are easier 153428f6c2f2SEnji Cooperto maintain when you do need to maintain them). 153528f6c2f2SEnji Cooper 153628f6c2f2SEnji CooperIf you are bothered by the "Uninteresting mock function call" message printed 153728f6c2f2SEnji Cooperwhen a mock method without an `EXPECT_CALL` is called, you may use a `NiceMock` 153828f6c2f2SEnji Cooperinstead to suppress all such messages for the mock object, or suppress the 153928f6c2f2SEnji Coopermessage for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO 154028f6c2f2SEnji CooperNOT suppress it by blindly adding an `EXPECT_CALL(...)`, or you'll have a test 154128f6c2f2SEnji Cooperthat's a pain to maintain. 154228f6c2f2SEnji Cooper 154328f6c2f2SEnji Cooper### Ignoring Uninteresting Calls 154428f6c2f2SEnji Cooper 154528f6c2f2SEnji CooperIf you are not interested in how a mock method is called, just don't say 154628f6c2f2SEnji Cooperanything about it. In this case, if the method is ever called, gMock will 154728f6c2f2SEnji Cooperperform its default action to allow the test program to continue. If you are not 154828f6c2f2SEnji Cooperhappy with the default action taken by gMock, you can override it using 154928f6c2f2SEnji Cooper`DefaultValue<T>::Set()` (described [here](#DefaultValue)) or `ON_CALL()`. 155028f6c2f2SEnji Cooper 155128f6c2f2SEnji CooperPlease note that once you expressed interest in a particular mock method (via 155228f6c2f2SEnji Cooper`EXPECT_CALL()`), all invocations to it must match some expectation. If this 155328f6c2f2SEnji Cooperfunction is called but the arguments don't match any `EXPECT_CALL()` statement, 155428f6c2f2SEnji Cooperit will be an error. 155528f6c2f2SEnji Cooper 155628f6c2f2SEnji Cooper### Disallowing Unexpected Calls 155728f6c2f2SEnji Cooper 155828f6c2f2SEnji CooperIf a mock method shouldn't be called at all, explicitly say so: 155928f6c2f2SEnji Cooper 156028f6c2f2SEnji Cooper```cpp 156128f6c2f2SEnji Cooperusing ::testing::_; 156228f6c2f2SEnji Cooper... 156328f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar(_)) 156428f6c2f2SEnji Cooper .Times(0); 156528f6c2f2SEnji Cooper``` 156628f6c2f2SEnji Cooper 156728f6c2f2SEnji CooperIf some calls to the method are allowed, but the rest are not, just list all the 156828f6c2f2SEnji Cooperexpected calls: 156928f6c2f2SEnji Cooper 157028f6c2f2SEnji Cooper```cpp 157128f6c2f2SEnji Cooperusing ::testing::AnyNumber; 157228f6c2f2SEnji Cooperusing ::testing::Gt; 157328f6c2f2SEnji Cooper... 157428f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar(5)); 157528f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar(Gt(10))) 157628f6c2f2SEnji Cooper .Times(AnyNumber()); 157728f6c2f2SEnji Cooper``` 157828f6c2f2SEnji Cooper 157928f6c2f2SEnji CooperA call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` statements 158028f6c2f2SEnji Cooperwill be an error. 158128f6c2f2SEnji Cooper 158228f6c2f2SEnji Cooper### Understanding Uninteresting vs Unexpected Calls {#uninteresting-vs-unexpected} 158328f6c2f2SEnji Cooper 158428f6c2f2SEnji Cooper*Uninteresting* calls and *unexpected* calls are different concepts in gMock. 158528f6c2f2SEnji Cooper*Very* different. 158628f6c2f2SEnji Cooper 158728f6c2f2SEnji CooperA call `x.Y(...)` is **uninteresting** if there's *not even a single* 158828f6c2f2SEnji Cooper`EXPECT_CALL(x, Y(...))` set. In other words, the test isn't interested in the 158928f6c2f2SEnji Cooper`x.Y()` method at all, as evident in that the test doesn't care to say anything 159028f6c2f2SEnji Cooperabout it. 159128f6c2f2SEnji Cooper 159228f6c2f2SEnji CooperA call `x.Y(...)` is **unexpected** if there are *some* `EXPECT_CALL(x, 159328f6c2f2SEnji CooperY(...))`s set, but none of them matches the call. Put another way, the test is 159428f6c2f2SEnji Cooperinterested in the `x.Y()` method (therefore it explicitly sets some 159528f6c2f2SEnji Cooper`EXPECT_CALL` to verify how it's called); however, the verification fails as the 159628f6c2f2SEnji Coopertest doesn't expect this particular call to happen. 159728f6c2f2SEnji Cooper 159828f6c2f2SEnji Cooper**An unexpected call is always an error,** as the code under test doesn't behave 159928f6c2f2SEnji Cooperthe way the test expects it to behave. 160028f6c2f2SEnji Cooper 160128f6c2f2SEnji Cooper**By default, an uninteresting call is not an error,** as it violates no 160228f6c2f2SEnji Cooperconstraint specified by the test. (gMock's philosophy is that saying nothing 160328f6c2f2SEnji Coopermeans there is no constraint.) However, it leads to a warning, as it *might* 160428f6c2f2SEnji Cooperindicate a problem (e.g. the test author might have forgotten to specify a 160528f6c2f2SEnji Cooperconstraint). 160628f6c2f2SEnji Cooper 160728f6c2f2SEnji CooperIn gMock, `NiceMock` and `StrictMock` can be used to make a mock class "nice" or 160828f6c2f2SEnji Cooper"strict". How does this affect uninteresting calls and unexpected calls? 160928f6c2f2SEnji Cooper 161028f6c2f2SEnji CooperA **nice mock** suppresses uninteresting call *warnings*. It is less chatty than 161128f6c2f2SEnji Cooperthe default mock, but otherwise is the same. If a test fails with a default 161228f6c2f2SEnji Coopermock, it will also fail using a nice mock instead. And vice versa. Don't expect 161328f6c2f2SEnji Coopermaking a mock nice to change the test's result. 161428f6c2f2SEnji Cooper 161528f6c2f2SEnji CooperA **strict mock** turns uninteresting call warnings into errors. So making a 161628f6c2f2SEnji Coopermock strict may change the test's result. 161728f6c2f2SEnji Cooper 161828f6c2f2SEnji CooperLet's look at an example: 161928f6c2f2SEnji Cooper 162028f6c2f2SEnji Cooper```cpp 162128f6c2f2SEnji CooperTEST(...) { 162228f6c2f2SEnji Cooper NiceMock<MockDomainRegistry> mock_registry; 162328f6c2f2SEnji Cooper EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) 162428f6c2f2SEnji Cooper .WillRepeatedly(Return("Larry Page")); 162528f6c2f2SEnji Cooper 162628f6c2f2SEnji Cooper // Use mock_registry in code under test. 162728f6c2f2SEnji Cooper ... &mock_registry ... 162828f6c2f2SEnji Cooper} 162928f6c2f2SEnji Cooper``` 163028f6c2f2SEnji Cooper 163128f6c2f2SEnji CooperThe sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have 163228f6c2f2SEnji Cooper`"google.com"` as the argument. If `GetDomainOwner("yahoo.com")` is called, it 163328f6c2f2SEnji Cooperwill be an unexpected call, and thus an error. *Having a nice mock doesn't 163428f6c2f2SEnji Cooperchange the severity of an unexpected call.* 163528f6c2f2SEnji Cooper 163628f6c2f2SEnji CooperSo how do we tell gMock that `GetDomainOwner()` can be called with some other 163728f6c2f2SEnji Cooperarguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`: 163828f6c2f2SEnji Cooper 163928f6c2f2SEnji Cooper```cpp 164028f6c2f2SEnji Cooper EXPECT_CALL(mock_registry, GetDomainOwner(_)) 164128f6c2f2SEnji Cooper .Times(AnyNumber()); // catches all other calls to this method. 164228f6c2f2SEnji Cooper EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) 164328f6c2f2SEnji Cooper .WillRepeatedly(Return("Larry Page")); 164428f6c2f2SEnji Cooper``` 164528f6c2f2SEnji Cooper 164628f6c2f2SEnji CooperRemember that `_` is the wildcard matcher that matches anything. With this, if 164728f6c2f2SEnji Cooper`GetDomainOwner("google.com")` is called, it will do what the second 164828f6c2f2SEnji Cooper`EXPECT_CALL` says; if it is called with a different argument, it will do what 164928f6c2f2SEnji Cooperthe first `EXPECT_CALL` says. 165028f6c2f2SEnji Cooper 165128f6c2f2SEnji CooperNote that the order of the two `EXPECT_CALL`s is important, as a newer 165228f6c2f2SEnji Cooper`EXPECT_CALL` takes precedence over an older one. 165328f6c2f2SEnji Cooper 165428f6c2f2SEnji CooperFor more on uninteresting calls, nice mocks, and strict mocks, read 165528f6c2f2SEnji Cooper["The Nice, the Strict, and the Naggy"](#NiceStrictNaggy). 165628f6c2f2SEnji Cooper 165728f6c2f2SEnji Cooper### Ignoring Uninteresting Arguments {#ParameterlessExpectations} 165828f6c2f2SEnji Cooper 165928f6c2f2SEnji CooperIf your test doesn't care about the parameters (it only cares about the number 166028f6c2f2SEnji Cooperor order of calls), you can often simply omit the parameter list: 166128f6c2f2SEnji Cooper 166228f6c2f2SEnji Cooper```cpp 166328f6c2f2SEnji Cooper // Expect foo.Bar( ... ) twice with any arguments. 166428f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar).Times(2); 166528f6c2f2SEnji Cooper 166628f6c2f2SEnji Cooper // Delegate to the given method whenever the factory is invoked. 166728f6c2f2SEnji Cooper ON_CALL(foo_factory, MakeFoo) 166828f6c2f2SEnji Cooper .WillByDefault(&BuildFooForTest); 166928f6c2f2SEnji Cooper``` 167028f6c2f2SEnji Cooper 167128f6c2f2SEnji CooperThis functionality is only available when a method is not overloaded; to prevent 167228f6c2f2SEnji Cooperunexpected behavior it is a compilation error to try to set an expectation on a 167328f6c2f2SEnji Coopermethod where the specific overload is ambiguous. You can work around this by 167428f6c2f2SEnji Coopersupplying a [simpler mock interface](#SimplerInterfaces) than the mocked class 167528f6c2f2SEnji Cooperprovides. 167628f6c2f2SEnji Cooper 167728f6c2f2SEnji CooperThis pattern is also useful when the arguments are interesting, but match logic 167828f6c2f2SEnji Cooperis substantially complex. You can leave the argument list unspecified and use 167928f6c2f2SEnji CooperSaveArg actions to [save the values for later verification](#SaveArgVerify). If 168028f6c2f2SEnji Cooperyou do that, you can easily differentiate calling the method the wrong number of 168128f6c2f2SEnji Coopertimes from calling it with the wrong arguments. 168228f6c2f2SEnji Cooper 168328f6c2f2SEnji Cooper### Expecting Ordered Calls {#OrderedCalls} 168428f6c2f2SEnji Cooper 168528f6c2f2SEnji CooperAlthough an `EXPECT_CALL()` statement defined later takes precedence when gMock 168628f6c2f2SEnji Coopertries to match a function call with an expectation, by default calls don't have 168728f6c2f2SEnji Cooperto happen in the order `EXPECT_CALL()` statements are written. For example, if 168828f6c2f2SEnji Cooperthe arguments match the matchers in the second `EXPECT_CALL()`, but not those in 168928f6c2f2SEnji Cooperthe first and third, then the second expectation will be used. 169028f6c2f2SEnji Cooper 169128f6c2f2SEnji CooperIf you would rather have all calls occur in the order of the expectations, put 169228f6c2f2SEnji Cooperthe `EXPECT_CALL()` statements in a block where you define a variable of type 169328f6c2f2SEnji Cooper`InSequence`: 169428f6c2f2SEnji Cooper 169528f6c2f2SEnji Cooper```cpp 169628f6c2f2SEnji Cooperusing ::testing::_; 169728f6c2f2SEnji Cooperusing ::testing::InSequence; 169828f6c2f2SEnji Cooper 169928f6c2f2SEnji Cooper { 170028f6c2f2SEnji Cooper InSequence s; 170128f6c2f2SEnji Cooper 170228f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(5)); 170328f6c2f2SEnji Cooper EXPECT_CALL(bar, DoThat(_)) 170428f6c2f2SEnji Cooper .Times(2); 170528f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(6)); 170628f6c2f2SEnji Cooper } 170728f6c2f2SEnji Cooper``` 170828f6c2f2SEnji Cooper 170928f6c2f2SEnji CooperIn this example, we expect a call to `foo.DoThis(5)`, followed by two calls to 171028f6c2f2SEnji Cooper`bar.DoThat()` where the argument can be anything, which are in turn followed by 171128f6c2f2SEnji Coopera call to `foo.DoThis(6)`. If a call occurred out-of-order, gMock will report an 171228f6c2f2SEnji Coopererror. 171328f6c2f2SEnji Cooper 171428f6c2f2SEnji Cooper### Expecting Partially Ordered Calls {#PartialOrder} 171528f6c2f2SEnji Cooper 171628f6c2f2SEnji CooperSometimes requiring everything to occur in a predetermined order can lead to 171728f6c2f2SEnji Cooperbrittle tests. For example, we may care about `A` occurring before both `B` and 171828f6c2f2SEnji Cooper`C`, but aren't interested in the relative order of `B` and `C`. In this case, 171928f6c2f2SEnji Cooperthe test should reflect our real intent, instead of being overly constraining. 172028f6c2f2SEnji Cooper 172128f6c2f2SEnji CoopergMock allows you to impose an arbitrary DAG (directed acyclic graph) on the 172228f6c2f2SEnji Coopercalls. One way to express the DAG is to use the 172328f6c2f2SEnji Cooper[`After` clause](reference/mocking.md#EXPECT_CALL.After) of `EXPECT_CALL`. 172428f6c2f2SEnji Cooper 172528f6c2f2SEnji CooperAnother way is via the `InSequence()` clause (not the same as the `InSequence` 172628f6c2f2SEnji Cooperclass), which we borrowed from jMock 2. It's less flexible than `After()`, but 172728f6c2f2SEnji Coopermore convenient when you have long chains of sequential calls, as it doesn't 172828f6c2f2SEnji Cooperrequire you to come up with different names for the expectations in the chains. 172928f6c2f2SEnji CooperHere's how it works: 173028f6c2f2SEnji Cooper 173128f6c2f2SEnji CooperIf we view `EXPECT_CALL()` statements as nodes in a graph, and add an edge from 173228f6c2f2SEnji Coopernode A to node B wherever A must occur before B, we can get a DAG. We use the 173328f6c2f2SEnji Cooperterm "sequence" to mean a directed path in this DAG. Now, if we decompose the 173428f6c2f2SEnji CooperDAG into sequences, we just need to know which sequences each `EXPECT_CALL()` 173528f6c2f2SEnji Cooperbelongs to in order to be able to reconstruct the original DAG. 173628f6c2f2SEnji Cooper 173728f6c2f2SEnji CooperSo, to specify the partial order on the expectations we need to do two things: 173828f6c2f2SEnji Cooperfirst to define some `Sequence` objects, and then for each `EXPECT_CALL()` say 173928f6c2f2SEnji Cooperwhich `Sequence` objects it is part of. 174028f6c2f2SEnji Cooper 174128f6c2f2SEnji CooperExpectations in the same sequence must occur in the order they are written. For 174228f6c2f2SEnji Cooperexample, 174328f6c2f2SEnji Cooper 174428f6c2f2SEnji Cooper```cpp 174528f6c2f2SEnji Cooperusing ::testing::Sequence; 174628f6c2f2SEnji Cooper... 174728f6c2f2SEnji Cooper Sequence s1, s2; 174828f6c2f2SEnji Cooper 174928f6c2f2SEnji Cooper EXPECT_CALL(foo, A()) 175028f6c2f2SEnji Cooper .InSequence(s1, s2); 175128f6c2f2SEnji Cooper EXPECT_CALL(bar, B()) 175228f6c2f2SEnji Cooper .InSequence(s1); 175328f6c2f2SEnji Cooper EXPECT_CALL(bar, C()) 175428f6c2f2SEnji Cooper .InSequence(s2); 175528f6c2f2SEnji Cooper EXPECT_CALL(foo, D()) 175628f6c2f2SEnji Cooper .InSequence(s2); 175728f6c2f2SEnji Cooper``` 175828f6c2f2SEnji Cooper 175928f6c2f2SEnji Cooperspecifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> C -> D`): 176028f6c2f2SEnji Cooper 176128f6c2f2SEnji Cooper```text 176228f6c2f2SEnji Cooper +---> B 176328f6c2f2SEnji Cooper | 176428f6c2f2SEnji Cooper A ---| 176528f6c2f2SEnji Cooper | 176628f6c2f2SEnji Cooper +---> C ---> D 176728f6c2f2SEnji Cooper``` 176828f6c2f2SEnji Cooper 176928f6c2f2SEnji CooperThis means that A must occur before B and C, and C must occur before D. There's 177028f6c2f2SEnji Cooperno restriction about the order other than these. 177128f6c2f2SEnji Cooper 177228f6c2f2SEnji Cooper### Controlling When an Expectation Retires 177328f6c2f2SEnji Cooper 177428f6c2f2SEnji CooperWhen a mock method is called, gMock only considers expectations that are still 177528f6c2f2SEnji Cooperactive. An expectation is active when created, and becomes inactive (aka 177628f6c2f2SEnji Cooper*retires*) when a call that has to occur later has occurred. For example, in 177728f6c2f2SEnji Cooper 177828f6c2f2SEnji Cooper```cpp 177928f6c2f2SEnji Cooperusing ::testing::_; 178028f6c2f2SEnji Cooperusing ::testing::Sequence; 178128f6c2f2SEnji Cooper... 178228f6c2f2SEnji Cooper Sequence s1, s2; 178328f6c2f2SEnji Cooper 178428f6c2f2SEnji Cooper EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 178528f6c2f2SEnji Cooper .Times(AnyNumber()) 178628f6c2f2SEnji Cooper .InSequence(s1, s2); 178728f6c2f2SEnji Cooper EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 178828f6c2f2SEnji Cooper .InSequence(s1); 178928f6c2f2SEnji Cooper EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 179028f6c2f2SEnji Cooper .InSequence(s2); 179128f6c2f2SEnji Cooper``` 179228f6c2f2SEnji Cooper 179328f6c2f2SEnji Cooperas soon as either #2 or #3 is matched, #1 will retire. If a warning `"File too 179428f6c2f2SEnji Cooperlarge."` is logged after this, it will be an error. 179528f6c2f2SEnji Cooper 179628f6c2f2SEnji CooperNote that an expectation doesn't retire automatically when it's saturated. For 179728f6c2f2SEnji Cooperexample, 179828f6c2f2SEnji Cooper 179928f6c2f2SEnji Cooper```cpp 180028f6c2f2SEnji Cooperusing ::testing::_; 180128f6c2f2SEnji Cooper... 180228f6c2f2SEnji Cooper EXPECT_CALL(log, Log(WARNING, _, _)); // #1 180328f6c2f2SEnji Cooper EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 180428f6c2f2SEnji Cooper``` 180528f6c2f2SEnji Cooper 180628f6c2f2SEnji Coopersays that there will be exactly one warning with the message `"File too 180728f6c2f2SEnji Cooperlarge."`. If the second warning contains this message too, #2 will match again 180828f6c2f2SEnji Cooperand result in an upper-bound-violated error. 180928f6c2f2SEnji Cooper 181028f6c2f2SEnji CooperIf this is not what you want, you can ask an expectation to retire as soon as it 181128f6c2f2SEnji Cooperbecomes saturated: 181228f6c2f2SEnji Cooper 181328f6c2f2SEnji Cooper```cpp 181428f6c2f2SEnji Cooperusing ::testing::_; 181528f6c2f2SEnji Cooper... 181628f6c2f2SEnji Cooper EXPECT_CALL(log, Log(WARNING, _, _)); // #1 181728f6c2f2SEnji Cooper EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 181828f6c2f2SEnji Cooper .RetiresOnSaturation(); 181928f6c2f2SEnji Cooper``` 182028f6c2f2SEnji Cooper 182128f6c2f2SEnji CooperHere #2 can be used only once, so if you have two warnings with the message 182228f6c2f2SEnji Cooper`"File too large."`, the first will match #2 and the second will match #1 - 182328f6c2f2SEnji Cooperthere will be no error. 182428f6c2f2SEnji Cooper 182528f6c2f2SEnji Cooper## Using Actions 182628f6c2f2SEnji Cooper 182728f6c2f2SEnji Cooper### Returning References from Mock Methods 182828f6c2f2SEnji Cooper 182928f6c2f2SEnji CooperIf a mock function's return type is a reference, you need to use `ReturnRef()` 183028f6c2f2SEnji Cooperinstead of `Return()` to return a result: 183128f6c2f2SEnji Cooper 183228f6c2f2SEnji Cooper```cpp 183328f6c2f2SEnji Cooperusing ::testing::ReturnRef; 183428f6c2f2SEnji Cooper 183528f6c2f2SEnji Cooperclass MockFoo : public Foo { 183628f6c2f2SEnji Cooper public: 183728f6c2f2SEnji Cooper MOCK_METHOD(Bar&, GetBar, (), (override)); 183828f6c2f2SEnji Cooper}; 183928f6c2f2SEnji Cooper... 184028f6c2f2SEnji Cooper MockFoo foo; 184128f6c2f2SEnji Cooper Bar bar; 184228f6c2f2SEnji Cooper EXPECT_CALL(foo, GetBar()) 184328f6c2f2SEnji Cooper .WillOnce(ReturnRef(bar)); 184428f6c2f2SEnji Cooper... 184528f6c2f2SEnji Cooper``` 184628f6c2f2SEnji Cooper 184728f6c2f2SEnji Cooper### Returning Live Values from Mock Methods 184828f6c2f2SEnji Cooper 184928f6c2f2SEnji CooperThe `Return(x)` action saves a copy of `x` when the action is created, and 185028f6c2f2SEnji Cooperalways returns the same value whenever it's executed. Sometimes you may want to 185128f6c2f2SEnji Cooperinstead return the *live* value of `x` (i.e. its value at the time when the 185228f6c2f2SEnji Cooperaction is *executed*.). Use either `ReturnRef()` or `ReturnPointee()` for this 185328f6c2f2SEnji Cooperpurpose. 185428f6c2f2SEnji Cooper 185528f6c2f2SEnji CooperIf the mock function's return type is a reference, you can do it using 185628f6c2f2SEnji Cooper`ReturnRef(x)`, as shown in the previous recipe ("Returning References from Mock 185728f6c2f2SEnji CooperMethods"). However, gMock doesn't let you use `ReturnRef()` in a mock function 185828f6c2f2SEnji Cooperwhose return type is not a reference, as doing that usually indicates a user 185928f6c2f2SEnji Coopererror. So, what shall you do? 186028f6c2f2SEnji Cooper 186128f6c2f2SEnji CooperThough you may be tempted, DO NOT use `std::ref()`: 186228f6c2f2SEnji Cooper 186328f6c2f2SEnji Cooper```cpp 186428f6c2f2SEnji Cooperusing ::testing::Return; 186528f6c2f2SEnji Cooper 186628f6c2f2SEnji Cooperclass MockFoo : public Foo { 186728f6c2f2SEnji Cooper public: 186828f6c2f2SEnji Cooper MOCK_METHOD(int, GetValue, (), (override)); 186928f6c2f2SEnji Cooper}; 187028f6c2f2SEnji Cooper... 187128f6c2f2SEnji Cooper int x = 0; 187228f6c2f2SEnji Cooper MockFoo foo; 187328f6c2f2SEnji Cooper EXPECT_CALL(foo, GetValue()) 187428f6c2f2SEnji Cooper .WillRepeatedly(Return(std::ref(x))); // Wrong! 187528f6c2f2SEnji Cooper x = 42; 187628f6c2f2SEnji Cooper EXPECT_EQ(foo.GetValue(), 42); 187728f6c2f2SEnji Cooper``` 187828f6c2f2SEnji Cooper 187928f6c2f2SEnji CooperUnfortunately, it doesn't work here. The above code will fail with error: 188028f6c2f2SEnji Cooper 188128f6c2f2SEnji Cooper```text 188228f6c2f2SEnji CooperValue of: foo.GetValue() 188328f6c2f2SEnji Cooper Actual: 0 188428f6c2f2SEnji CooperExpected: 42 188528f6c2f2SEnji Cooper``` 188628f6c2f2SEnji Cooper 188728f6c2f2SEnji CooperThe reason is that `Return(*value*)` converts `value` to the actual return type 188828f6c2f2SEnji Cooperof the mock function at the time when the action is *created*, not when it is 188928f6c2f2SEnji Cooper*executed*. (This behavior was chosen for the action to be safe when `value` is 189028f6c2f2SEnji Coopera proxy object that references some temporary objects.) As a result, 189128f6c2f2SEnji Cooper`std::ref(x)` is converted to an `int` value (instead of a `const int&`) when 189228f6c2f2SEnji Cooperthe expectation is set, and `Return(std::ref(x))` will always return 0. 189328f6c2f2SEnji Cooper 189428f6c2f2SEnji Cooper`ReturnPointee(pointer)` was provided to solve this problem specifically. It 189528f6c2f2SEnji Cooperreturns the value pointed to by `pointer` at the time the action is *executed*: 189628f6c2f2SEnji Cooper 189728f6c2f2SEnji Cooper```cpp 189828f6c2f2SEnji Cooperusing ::testing::ReturnPointee; 189928f6c2f2SEnji Cooper... 190028f6c2f2SEnji Cooper int x = 0; 190128f6c2f2SEnji Cooper MockFoo foo; 190228f6c2f2SEnji Cooper EXPECT_CALL(foo, GetValue()) 190328f6c2f2SEnji Cooper .WillRepeatedly(ReturnPointee(&x)); // Note the & here. 190428f6c2f2SEnji Cooper x = 42; 190528f6c2f2SEnji Cooper EXPECT_EQ(foo.GetValue(), 42); // This will succeed now. 190628f6c2f2SEnji Cooper``` 190728f6c2f2SEnji Cooper 190828f6c2f2SEnji Cooper### Combining Actions 190928f6c2f2SEnji Cooper 191028f6c2f2SEnji CooperWant to do more than one thing when a function is called? That's fine. `DoAll()` 191128f6c2f2SEnji Cooperallows you to do a sequence of actions every time. Only the return value of the 191228f6c2f2SEnji Cooperlast action in the sequence will be used. 191328f6c2f2SEnji Cooper 191428f6c2f2SEnji Cooper```cpp 191528f6c2f2SEnji Cooperusing ::testing::_; 191628f6c2f2SEnji Cooperusing ::testing::DoAll; 191728f6c2f2SEnji Cooper 191828f6c2f2SEnji Cooperclass MockFoo : public Foo { 191928f6c2f2SEnji Cooper public: 192028f6c2f2SEnji Cooper MOCK_METHOD(bool, Bar, (int n), (override)); 192128f6c2f2SEnji Cooper}; 192228f6c2f2SEnji Cooper... 192328f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar(_)) 192428f6c2f2SEnji Cooper .WillOnce(DoAll(action_1, 192528f6c2f2SEnji Cooper action_2, 192628f6c2f2SEnji Cooper ... 192728f6c2f2SEnji Cooper action_n)); 192828f6c2f2SEnji Cooper``` 192928f6c2f2SEnji Cooper 1930*5ca8c28cSEnji CooperThe return value of the last action **must** match the return type of the mocked 1931*5ca8c28cSEnji Coopermethod. In the example above, `action_n` could be `Return(true)`, or a lambda 1932*5ca8c28cSEnji Cooperthat returns a `bool`, but not `SaveArg`, which returns `void`. Otherwise the 1933*5ca8c28cSEnji Coopersignature of `DoAll` would not match the signature expected by `WillOnce`, which 1934*5ca8c28cSEnji Cooperis the signature of the mocked method, and it wouldn't compile. 1935*5ca8c28cSEnji Cooper 193628f6c2f2SEnji Cooper### Verifying Complex Arguments {#SaveArgVerify} 193728f6c2f2SEnji Cooper 193828f6c2f2SEnji CooperIf you want to verify that a method is called with a particular argument but the 193928f6c2f2SEnji Coopermatch criteria is complex, it can be difficult to distinguish between 194028f6c2f2SEnji Coopercardinality failures (calling the method the wrong number of times) and argument 194128f6c2f2SEnji Coopermatch failures. Similarly, if you are matching multiple parameters, it may not 194228f6c2f2SEnji Cooperbe easy to distinguishing which argument failed to match. For example: 194328f6c2f2SEnji Cooper 194428f6c2f2SEnji Cooper```cpp 194528f6c2f2SEnji Cooper // Not ideal: this could fail because of a problem with arg1 or arg2, or maybe 194628f6c2f2SEnji Cooper // just the method wasn't called. 194728f6c2f2SEnji Cooper EXPECT_CALL(foo, SendValues(_, ElementsAre(1, 4, 4, 7), EqualsProto( ... ))); 194828f6c2f2SEnji Cooper``` 194928f6c2f2SEnji Cooper 195028f6c2f2SEnji CooperYou can instead save the arguments and test them individually: 195128f6c2f2SEnji Cooper 195228f6c2f2SEnji Cooper```cpp 195328f6c2f2SEnji Cooper EXPECT_CALL(foo, SendValues) 195428f6c2f2SEnji Cooper .WillOnce(DoAll(SaveArg<1>(&actual_array), SaveArg<2>(&actual_proto))); 195528f6c2f2SEnji Cooper ... run the test 195628f6c2f2SEnji Cooper EXPECT_THAT(actual_array, ElementsAre(1, 4, 4, 7)); 195728f6c2f2SEnji Cooper EXPECT_THAT(actual_proto, EqualsProto( ... )); 195828f6c2f2SEnji Cooper``` 195928f6c2f2SEnji Cooper 196028f6c2f2SEnji Cooper### Mocking Side Effects {#MockingSideEffects} 196128f6c2f2SEnji Cooper 196228f6c2f2SEnji CooperSometimes a method exhibits its effect not via returning a value but via side 196328f6c2f2SEnji Coopereffects. For example, it may change some global state or modify an output 196428f6c2f2SEnji Cooperargument. To mock side effects, in general you can define your own action by 196528f6c2f2SEnji Cooperimplementing `::testing::ActionInterface`. 196628f6c2f2SEnji Cooper 196728f6c2f2SEnji CooperIf all you need to do is to change an output argument, the built-in 196828f6c2f2SEnji Cooper`SetArgPointee()` action is convenient: 196928f6c2f2SEnji Cooper 197028f6c2f2SEnji Cooper```cpp 197128f6c2f2SEnji Cooperusing ::testing::_; 197228f6c2f2SEnji Cooperusing ::testing::SetArgPointee; 197328f6c2f2SEnji Cooper 197428f6c2f2SEnji Cooperclass MockMutator : public Mutator { 197528f6c2f2SEnji Cooper public: 197628f6c2f2SEnji Cooper MOCK_METHOD(void, Mutate, (bool mutate, int* value), (override)); 197728f6c2f2SEnji Cooper ... 197828f6c2f2SEnji Cooper} 197928f6c2f2SEnji Cooper... 198028f6c2f2SEnji Cooper MockMutator mutator; 198128f6c2f2SEnji Cooper EXPECT_CALL(mutator, Mutate(true, _)) 198228f6c2f2SEnji Cooper .WillOnce(SetArgPointee<1>(5)); 198328f6c2f2SEnji Cooper``` 198428f6c2f2SEnji Cooper 198528f6c2f2SEnji CooperIn this example, when `mutator.Mutate()` is called, we will assign 5 to the 198628f6c2f2SEnji Cooper`int` variable pointed to by argument #1 (0-based). 198728f6c2f2SEnji Cooper 198828f6c2f2SEnji Cooper`SetArgPointee()` conveniently makes an internal copy of the value you pass to 198928f6c2f2SEnji Cooperit, removing the need to keep the value in scope and alive. The implication 199028f6c2f2SEnji Cooperhowever is that the value must have a copy constructor and assignment operator. 199128f6c2f2SEnji Cooper 199228f6c2f2SEnji CooperIf the mock method also needs to return a value as well, you can chain 199328f6c2f2SEnji Cooper`SetArgPointee()` with `Return()` using `DoAll()`, remembering to put the 199428f6c2f2SEnji Cooper`Return()` statement last: 199528f6c2f2SEnji Cooper 199628f6c2f2SEnji Cooper```cpp 199728f6c2f2SEnji Cooperusing ::testing::_; 199828f6c2f2SEnji Cooperusing ::testing::DoAll; 199928f6c2f2SEnji Cooperusing ::testing::Return; 200028f6c2f2SEnji Cooperusing ::testing::SetArgPointee; 200128f6c2f2SEnji Cooper 200228f6c2f2SEnji Cooperclass MockMutator : public Mutator { 200328f6c2f2SEnji Cooper public: 200428f6c2f2SEnji Cooper ... 200528f6c2f2SEnji Cooper MOCK_METHOD(bool, MutateInt, (int* value), (override)); 200628f6c2f2SEnji Cooper} 200728f6c2f2SEnji Cooper... 200828f6c2f2SEnji Cooper MockMutator mutator; 200928f6c2f2SEnji Cooper EXPECT_CALL(mutator, MutateInt(_)) 201028f6c2f2SEnji Cooper .WillOnce(DoAll(SetArgPointee<0>(5), 201128f6c2f2SEnji Cooper Return(true))); 201228f6c2f2SEnji Cooper``` 201328f6c2f2SEnji Cooper 201428f6c2f2SEnji CooperNote, however, that if you use the `ReturnOKWith()` method, it will override the 201528f6c2f2SEnji Coopervalues provided by `SetArgPointee()` in the response parameters of your function 201628f6c2f2SEnji Coopercall. 201728f6c2f2SEnji Cooper 201828f6c2f2SEnji CooperIf the output argument is an array, use the `SetArrayArgument<N>(first, last)` 201928f6c2f2SEnji Cooperaction instead. It copies the elements in source range `[first, last)` to the 202028f6c2f2SEnji Cooperarray pointed to by the `N`-th (0-based) argument: 202128f6c2f2SEnji Cooper 202228f6c2f2SEnji Cooper```cpp 202328f6c2f2SEnji Cooperusing ::testing::NotNull; 202428f6c2f2SEnji Cooperusing ::testing::SetArrayArgument; 202528f6c2f2SEnji Cooper 202628f6c2f2SEnji Cooperclass MockArrayMutator : public ArrayMutator { 202728f6c2f2SEnji Cooper public: 202828f6c2f2SEnji Cooper MOCK_METHOD(void, Mutate, (int* values, int num_values), (override)); 202928f6c2f2SEnji Cooper ... 203028f6c2f2SEnji Cooper} 203128f6c2f2SEnji Cooper... 203228f6c2f2SEnji Cooper MockArrayMutator mutator; 203328f6c2f2SEnji Cooper int values[5] = {1, 2, 3, 4, 5}; 203428f6c2f2SEnji Cooper EXPECT_CALL(mutator, Mutate(NotNull(), 5)) 203528f6c2f2SEnji Cooper .WillOnce(SetArrayArgument<0>(values, values + 5)); 203628f6c2f2SEnji Cooper``` 203728f6c2f2SEnji Cooper 203828f6c2f2SEnji CooperThis also works when the argument is an output iterator: 203928f6c2f2SEnji Cooper 204028f6c2f2SEnji Cooper```cpp 204128f6c2f2SEnji Cooperusing ::testing::_; 204228f6c2f2SEnji Cooperusing ::testing::SetArrayArgument; 204328f6c2f2SEnji Cooper 204428f6c2f2SEnji Cooperclass MockRolodex : public Rolodex { 204528f6c2f2SEnji Cooper public: 204628f6c2f2SEnji Cooper MOCK_METHOD(void, GetNames, (std::back_insert_iterator<vector<string>>), 204728f6c2f2SEnji Cooper (override)); 204828f6c2f2SEnji Cooper ... 204928f6c2f2SEnji Cooper} 205028f6c2f2SEnji Cooper... 205128f6c2f2SEnji Cooper MockRolodex rolodex; 205228f6c2f2SEnji Cooper vector<string> names = {"George", "John", "Thomas"}; 205328f6c2f2SEnji Cooper EXPECT_CALL(rolodex, GetNames(_)) 205428f6c2f2SEnji Cooper .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); 205528f6c2f2SEnji Cooper``` 205628f6c2f2SEnji Cooper 205728f6c2f2SEnji Cooper### Changing a Mock Object's Behavior Based on the State 205828f6c2f2SEnji Cooper 205928f6c2f2SEnji CooperIf you expect a call to change the behavior of a mock object, you can use 206028f6c2f2SEnji Cooper`::testing::InSequence` to specify different behaviors before and after the 206128f6c2f2SEnji Coopercall: 206228f6c2f2SEnji Cooper 206328f6c2f2SEnji Cooper```cpp 206428f6c2f2SEnji Cooperusing ::testing::InSequence; 206528f6c2f2SEnji Cooperusing ::testing::Return; 206628f6c2f2SEnji Cooper 206728f6c2f2SEnji Cooper... 206828f6c2f2SEnji Cooper { 206928f6c2f2SEnji Cooper InSequence seq; 207028f6c2f2SEnji Cooper EXPECT_CALL(my_mock, IsDirty()) 207128f6c2f2SEnji Cooper .WillRepeatedly(Return(true)); 207228f6c2f2SEnji Cooper EXPECT_CALL(my_mock, Flush()); 207328f6c2f2SEnji Cooper EXPECT_CALL(my_mock, IsDirty()) 207428f6c2f2SEnji Cooper .WillRepeatedly(Return(false)); 207528f6c2f2SEnji Cooper } 207628f6c2f2SEnji Cooper my_mock.FlushIfDirty(); 207728f6c2f2SEnji Cooper``` 207828f6c2f2SEnji Cooper 207928f6c2f2SEnji CooperThis makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called 208028f6c2f2SEnji Cooperand return `false` afterwards. 208128f6c2f2SEnji Cooper 208228f6c2f2SEnji CooperIf the behavior change is more complex, you can store the effects in a variable 208328f6c2f2SEnji Cooperand make a mock method get its return value from that variable: 208428f6c2f2SEnji Cooper 208528f6c2f2SEnji Cooper```cpp 208628f6c2f2SEnji Cooperusing ::testing::_; 208728f6c2f2SEnji Cooperusing ::testing::SaveArg; 208828f6c2f2SEnji Cooperusing ::testing::Return; 208928f6c2f2SEnji Cooper 209028f6c2f2SEnji CooperACTION_P(ReturnPointee, p) { return *p; } 209128f6c2f2SEnji Cooper... 209228f6c2f2SEnji Cooper int previous_value = 0; 209328f6c2f2SEnji Cooper EXPECT_CALL(my_mock, GetPrevValue) 209428f6c2f2SEnji Cooper .WillRepeatedly(ReturnPointee(&previous_value)); 209528f6c2f2SEnji Cooper EXPECT_CALL(my_mock, UpdateValue) 209628f6c2f2SEnji Cooper .WillRepeatedly(SaveArg<0>(&previous_value)); 209728f6c2f2SEnji Cooper my_mock.DoSomethingToUpdateValue(); 209828f6c2f2SEnji Cooper``` 209928f6c2f2SEnji Cooper 210028f6c2f2SEnji CooperHere `my_mock.GetPrevValue()` will always return the argument of the last 210128f6c2f2SEnji Cooper`UpdateValue()` call. 210228f6c2f2SEnji Cooper 210328f6c2f2SEnji Cooper### Setting the Default Value for a Return Type {#DefaultValue} 210428f6c2f2SEnji Cooper 210528f6c2f2SEnji CooperIf a mock method's return type is a built-in C++ type or pointer, by default it 210628f6c2f2SEnji Cooperwill return 0 when invoked. Also, in C++ 11 and above, a mock method whose 210728f6c2f2SEnji Cooperreturn type has a default constructor will return a default-constructed value by 210828f6c2f2SEnji Cooperdefault. You only need to specify an action if this default value doesn't work 210928f6c2f2SEnji Cooperfor you. 211028f6c2f2SEnji Cooper 211128f6c2f2SEnji CooperSometimes, you may want to change this default value, or you may want to specify 211228f6c2f2SEnji Coopera default value for types gMock doesn't know about. You can do this using the 211328f6c2f2SEnji Cooper`::testing::DefaultValue` class template: 211428f6c2f2SEnji Cooper 211528f6c2f2SEnji Cooper```cpp 211628f6c2f2SEnji Cooperusing ::testing::DefaultValue; 211728f6c2f2SEnji Cooper 211828f6c2f2SEnji Cooperclass MockFoo : public Foo { 211928f6c2f2SEnji Cooper public: 212028f6c2f2SEnji Cooper MOCK_METHOD(Bar, CalculateBar, (), (override)); 212128f6c2f2SEnji Cooper}; 212228f6c2f2SEnji Cooper 212328f6c2f2SEnji Cooper 212428f6c2f2SEnji Cooper... 212528f6c2f2SEnji Cooper Bar default_bar; 212628f6c2f2SEnji Cooper // Sets the default return value for type Bar. 212728f6c2f2SEnji Cooper DefaultValue<Bar>::Set(default_bar); 212828f6c2f2SEnji Cooper 212928f6c2f2SEnji Cooper MockFoo foo; 213028f6c2f2SEnji Cooper 213128f6c2f2SEnji Cooper // We don't need to specify an action here, as the default 213228f6c2f2SEnji Cooper // return value works for us. 213328f6c2f2SEnji Cooper EXPECT_CALL(foo, CalculateBar()); 213428f6c2f2SEnji Cooper 213528f6c2f2SEnji Cooper foo.CalculateBar(); // This should return default_bar. 213628f6c2f2SEnji Cooper 213728f6c2f2SEnji Cooper // Unsets the default return value. 213828f6c2f2SEnji Cooper DefaultValue<Bar>::Clear(); 213928f6c2f2SEnji Cooper``` 214028f6c2f2SEnji Cooper 214128f6c2f2SEnji CooperPlease note that changing the default value for a type can make your tests hard 214228f6c2f2SEnji Cooperto understand. We recommend you to use this feature judiciously. For example, 214328f6c2f2SEnji Cooperyou may want to make sure the `Set()` and `Clear()` calls are right next to the 214428f6c2f2SEnji Coopercode that uses your mock. 214528f6c2f2SEnji Cooper 214628f6c2f2SEnji Cooper### Setting the Default Actions for a Mock Method 214728f6c2f2SEnji Cooper 214828f6c2f2SEnji CooperYou've learned how to change the default value of a given type. However, this 214928f6c2f2SEnji Coopermay be too coarse for your purpose: perhaps you have two mock methods with the 215028f6c2f2SEnji Coopersame return type and you want them to have different behaviors. The `ON_CALL()` 215128f6c2f2SEnji Coopermacro allows you to customize your mock's behavior at the method level: 215228f6c2f2SEnji Cooper 215328f6c2f2SEnji Cooper```cpp 215428f6c2f2SEnji Cooperusing ::testing::_; 215528f6c2f2SEnji Cooperusing ::testing::AnyNumber; 215628f6c2f2SEnji Cooperusing ::testing::Gt; 215728f6c2f2SEnji Cooperusing ::testing::Return; 215828f6c2f2SEnji Cooper... 215928f6c2f2SEnji Cooper ON_CALL(foo, Sign(_)) 216028f6c2f2SEnji Cooper .WillByDefault(Return(-1)); 216128f6c2f2SEnji Cooper ON_CALL(foo, Sign(0)) 216228f6c2f2SEnji Cooper .WillByDefault(Return(0)); 216328f6c2f2SEnji Cooper ON_CALL(foo, Sign(Gt(0))) 216428f6c2f2SEnji Cooper .WillByDefault(Return(1)); 216528f6c2f2SEnji Cooper 216628f6c2f2SEnji Cooper EXPECT_CALL(foo, Sign(_)) 216728f6c2f2SEnji Cooper .Times(AnyNumber()); 216828f6c2f2SEnji Cooper 216928f6c2f2SEnji Cooper foo.Sign(5); // This should return 1. 217028f6c2f2SEnji Cooper foo.Sign(-9); // This should return -1. 217128f6c2f2SEnji Cooper foo.Sign(0); // This should return 0. 217228f6c2f2SEnji Cooper``` 217328f6c2f2SEnji Cooper 217428f6c2f2SEnji CooperAs you may have guessed, when there are more than one `ON_CALL()` statements, 217528f6c2f2SEnji Cooperthe newer ones in the order take precedence over the older ones. In other words, 217628f6c2f2SEnji Cooperthe **last** one that matches the function arguments will be used. This matching 217728f6c2f2SEnji Cooperorder allows you to set up the common behavior in a mock object's constructor or 217828f6c2f2SEnji Cooperthe test fixture's set-up phase and specialize the mock's behavior later. 217928f6c2f2SEnji Cooper 218028f6c2f2SEnji CooperNote that both `ON_CALL` and `EXPECT_CALL` have the same "later statements take 218128f6c2f2SEnji Cooperprecedence" rule, but they don't interact. That is, `EXPECT_CALL`s have their 218228f6c2f2SEnji Cooperown precedence order distinct from the `ON_CALL` precedence order. 218328f6c2f2SEnji Cooper 218428f6c2f2SEnji Cooper### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions} 218528f6c2f2SEnji Cooper 218628f6c2f2SEnji CooperIf the built-in actions don't suit you, you can use an existing callable 218728f6c2f2SEnji Cooper(function, `std::function`, method, functor, lambda) as an action. 218828f6c2f2SEnji Cooper 218928f6c2f2SEnji Cooper```cpp 219028f6c2f2SEnji Cooperusing ::testing::_; using ::testing::Invoke; 219128f6c2f2SEnji Cooper 219228f6c2f2SEnji Cooperclass MockFoo : public Foo { 219328f6c2f2SEnji Cooper public: 219428f6c2f2SEnji Cooper MOCK_METHOD(int, Sum, (int x, int y), (override)); 219528f6c2f2SEnji Cooper MOCK_METHOD(bool, ComplexJob, (int x), (override)); 219628f6c2f2SEnji Cooper}; 219728f6c2f2SEnji Cooper 219828f6c2f2SEnji Cooperint CalculateSum(int x, int y) { return x + y; } 219928f6c2f2SEnji Cooperint Sum3(int x, int y, int z) { return x + y + z; } 220028f6c2f2SEnji Cooper 220128f6c2f2SEnji Cooperclass Helper { 220228f6c2f2SEnji Cooper public: 220328f6c2f2SEnji Cooper bool ComplexJob(int x); 220428f6c2f2SEnji Cooper}; 220528f6c2f2SEnji Cooper 220628f6c2f2SEnji Cooper... 220728f6c2f2SEnji Cooper MockFoo foo; 220828f6c2f2SEnji Cooper Helper helper; 220928f6c2f2SEnji Cooper EXPECT_CALL(foo, Sum(_, _)) 221028f6c2f2SEnji Cooper .WillOnce(&CalculateSum) 221128f6c2f2SEnji Cooper .WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1))); 221228f6c2f2SEnji Cooper EXPECT_CALL(foo, ComplexJob(_)) 221328f6c2f2SEnji Cooper .WillOnce(Invoke(&helper, &Helper::ComplexJob)) 221428f6c2f2SEnji Cooper .WillOnce([] { return true; }) 221528f6c2f2SEnji Cooper .WillRepeatedly([](int x) { return x > 0; }); 221628f6c2f2SEnji Cooper 221728f6c2f2SEnji Cooper foo.Sum(5, 6); // Invokes CalculateSum(5, 6). 221828f6c2f2SEnji Cooper foo.Sum(2, 3); // Invokes Sum3(1, 2, 3). 221928f6c2f2SEnji Cooper foo.ComplexJob(10); // Invokes helper.ComplexJob(10). 222028f6c2f2SEnji Cooper foo.ComplexJob(-1); // Invokes the inline lambda. 222128f6c2f2SEnji Cooper``` 222228f6c2f2SEnji Cooper 222328f6c2f2SEnji CooperThe only requirement is that the type of the function, etc must be *compatible* 222428f6c2f2SEnji Cooperwith the signature of the mock function, meaning that the latter's arguments (if 222528f6c2f2SEnji Cooperit takes any) can be implicitly converted to the corresponding arguments of the 222628f6c2f2SEnji Cooperformer, and the former's return type can be implicitly converted to that of the 222728f6c2f2SEnji Cooperlatter. So, you can invoke something whose type is *not* exactly the same as the 222828f6c2f2SEnji Coopermock function, as long as it's safe to do so - nice, huh? 222928f6c2f2SEnji Cooper 223028f6c2f2SEnji CooperNote that: 223128f6c2f2SEnji Cooper 223228f6c2f2SEnji Cooper* The action takes ownership of the callback and will delete it when the 223328f6c2f2SEnji Cooper action itself is destructed. 223428f6c2f2SEnji Cooper* If the type of a callback is derived from a base callback type `C`, you need 223528f6c2f2SEnji Cooper to implicitly cast it to `C` to resolve the overloading, e.g. 223628f6c2f2SEnji Cooper 223728f6c2f2SEnji Cooper ```cpp 223828f6c2f2SEnji Cooper using ::testing::Invoke; 223928f6c2f2SEnji Cooper ... 224028f6c2f2SEnji Cooper ResultCallback<bool>* is_ok = ...; 224128f6c2f2SEnji Cooper ... Invoke(is_ok) ...; // This works. 224228f6c2f2SEnji Cooper 224328f6c2f2SEnji Cooper BlockingClosure* done = new BlockingClosure; 224428f6c2f2SEnji Cooper ... Invoke(implicit_cast<Closure*>(done)) ...; // The cast is necessary. 224528f6c2f2SEnji Cooper ``` 224628f6c2f2SEnji Cooper 224728f6c2f2SEnji Cooper### Using Functions with Extra Info as Actions 224828f6c2f2SEnji Cooper 224928f6c2f2SEnji CooperThe function or functor you call using `Invoke()` must have the same number of 225028f6c2f2SEnji Cooperarguments as the mock function you use it for. Sometimes you may have a function 225128f6c2f2SEnji Cooperthat takes more arguments, and you are willing to pass in the extra arguments 225228f6c2f2SEnji Cooperyourself to fill the gap. You can do this in gMock using callbacks with 225328f6c2f2SEnji Cooperpre-bound arguments. Here's an example: 225428f6c2f2SEnji Cooper 225528f6c2f2SEnji Cooper```cpp 225628f6c2f2SEnji Cooperusing ::testing::Invoke; 225728f6c2f2SEnji Cooper 225828f6c2f2SEnji Cooperclass MockFoo : public Foo { 225928f6c2f2SEnji Cooper public: 226028f6c2f2SEnji Cooper MOCK_METHOD(char, DoThis, (int n), (override)); 226128f6c2f2SEnji Cooper}; 226228f6c2f2SEnji Cooper 226328f6c2f2SEnji Cooperchar SignOfSum(int x, int y) { 226428f6c2f2SEnji Cooper const int sum = x + y; 226528f6c2f2SEnji Cooper return (sum > 0) ? '+' : (sum < 0) ? '-' : '0'; 226628f6c2f2SEnji Cooper} 226728f6c2f2SEnji Cooper 226828f6c2f2SEnji CooperTEST_F(FooTest, Test) { 226928f6c2f2SEnji Cooper MockFoo foo; 227028f6c2f2SEnji Cooper 227128f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(2)) 227228f6c2f2SEnji Cooper .WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5))); 227328f6c2f2SEnji Cooper EXPECT_EQ(foo.DoThis(2), '+'); // Invokes SignOfSum(5, 2). 227428f6c2f2SEnji Cooper} 227528f6c2f2SEnji Cooper``` 227628f6c2f2SEnji Cooper 227728f6c2f2SEnji Cooper### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments 227828f6c2f2SEnji Cooper 227928f6c2f2SEnji Cooper`Invoke()` passes the mock function's arguments to the function, etc being 228028f6c2f2SEnji Cooperinvoked such that the callee has the full context of the call to work with. If 228128f6c2f2SEnji Cooperthe invoked function is not interested in some or all of the arguments, it can 228228f6c2f2SEnji Coopersimply ignore them. 228328f6c2f2SEnji Cooper 228428f6c2f2SEnji CooperYet, a common pattern is that a test author wants to invoke a function without 228528f6c2f2SEnji Cooperthe arguments of the mock function. She could do that using a wrapper function 228628f6c2f2SEnji Cooperthat throws away the arguments before invoking an underlining nullary function. 228728f6c2f2SEnji CooperNeedless to say, this can be tedious and obscures the intent of the test. 228828f6c2f2SEnji Cooper 228928f6c2f2SEnji CooperThere are two solutions to this problem. First, you can pass any callable of 229028f6c2f2SEnji Cooperzero args as an action. Alternatively, use `InvokeWithoutArgs()`, which is like 229128f6c2f2SEnji Cooper`Invoke()` except that it doesn't pass the mock function's arguments to the 229228f6c2f2SEnji Coopercallee. Here's an example of each: 229328f6c2f2SEnji Cooper 229428f6c2f2SEnji Cooper```cpp 229528f6c2f2SEnji Cooperusing ::testing::_; 229628f6c2f2SEnji Cooperusing ::testing::InvokeWithoutArgs; 229728f6c2f2SEnji Cooper 229828f6c2f2SEnji Cooperclass MockFoo : public Foo { 229928f6c2f2SEnji Cooper public: 230028f6c2f2SEnji Cooper MOCK_METHOD(bool, ComplexJob, (int n), (override)); 230128f6c2f2SEnji Cooper}; 230228f6c2f2SEnji Cooper 230328f6c2f2SEnji Cooperbool Job1() { ... } 230428f6c2f2SEnji Cooperbool Job2(int n, char c) { ... } 230528f6c2f2SEnji Cooper 230628f6c2f2SEnji Cooper... 230728f6c2f2SEnji Cooper MockFoo foo; 230828f6c2f2SEnji Cooper EXPECT_CALL(foo, ComplexJob(_)) 230928f6c2f2SEnji Cooper .WillOnce([] { Job1(); }); 231028f6c2f2SEnji Cooper .WillOnce(InvokeWithoutArgs(NewPermanentCallback(Job2, 5, 'a'))); 231128f6c2f2SEnji Cooper 231228f6c2f2SEnji Cooper foo.ComplexJob(10); // Invokes Job1(). 231328f6c2f2SEnji Cooper foo.ComplexJob(20); // Invokes Job2(5, 'a'). 231428f6c2f2SEnji Cooper``` 231528f6c2f2SEnji Cooper 231628f6c2f2SEnji CooperNote that: 231728f6c2f2SEnji Cooper 231828f6c2f2SEnji Cooper* The action takes ownership of the callback and will delete it when the 231928f6c2f2SEnji Cooper action itself is destructed. 232028f6c2f2SEnji Cooper* If the type of a callback is derived from a base callback type `C`, you need 232128f6c2f2SEnji Cooper to implicitly cast it to `C` to resolve the overloading, e.g. 232228f6c2f2SEnji Cooper 232328f6c2f2SEnji Cooper ```cpp 232428f6c2f2SEnji Cooper using ::testing::InvokeWithoutArgs; 232528f6c2f2SEnji Cooper ... 232628f6c2f2SEnji Cooper ResultCallback<bool>* is_ok = ...; 232728f6c2f2SEnji Cooper ... InvokeWithoutArgs(is_ok) ...; // This works. 232828f6c2f2SEnji Cooper 232928f6c2f2SEnji Cooper BlockingClosure* done = ...; 233028f6c2f2SEnji Cooper ... InvokeWithoutArgs(implicit_cast<Closure*>(done)) ...; 233128f6c2f2SEnji Cooper // The cast is necessary. 233228f6c2f2SEnji Cooper ``` 233328f6c2f2SEnji Cooper 233428f6c2f2SEnji Cooper### Invoking an Argument of the Mock Function 233528f6c2f2SEnji Cooper 233628f6c2f2SEnji CooperSometimes a mock function will receive a function pointer, a functor (in other 233728f6c2f2SEnji Cooperwords, a "callable") as an argument, e.g. 233828f6c2f2SEnji Cooper 233928f6c2f2SEnji Cooper```cpp 234028f6c2f2SEnji Cooperclass MockFoo : public Foo { 234128f6c2f2SEnji Cooper public: 234228f6c2f2SEnji Cooper MOCK_METHOD(bool, DoThis, (int n, (ResultCallback1<bool, int>* callback)), 234328f6c2f2SEnji Cooper (override)); 234428f6c2f2SEnji Cooper}; 234528f6c2f2SEnji Cooper``` 234628f6c2f2SEnji Cooper 234728f6c2f2SEnji Cooperand you may want to invoke this callable argument: 234828f6c2f2SEnji Cooper 234928f6c2f2SEnji Cooper```cpp 235028f6c2f2SEnji Cooperusing ::testing::_; 235128f6c2f2SEnji Cooper... 235228f6c2f2SEnji Cooper MockFoo foo; 235328f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(_, _)) 235428f6c2f2SEnji Cooper .WillOnce(...); 235528f6c2f2SEnji Cooper // Will execute callback->Run(5), where callback is the 235628f6c2f2SEnji Cooper // second argument DoThis() receives. 235728f6c2f2SEnji Cooper``` 235828f6c2f2SEnji Cooper 235928f6c2f2SEnji Cooper{: .callout .note} 236028f6c2f2SEnji CooperNOTE: The section below is legacy documentation from before C++ had lambdas: 236128f6c2f2SEnji Cooper 236228f6c2f2SEnji CooperArghh, you need to refer to a mock function argument but C++ has no lambda 236328f6c2f2SEnji Cooper(yet), so you have to define your own action. :-( Or do you really? 236428f6c2f2SEnji Cooper 236528f6c2f2SEnji CooperWell, gMock has an action to solve *exactly* this problem: 236628f6c2f2SEnji Cooper 236728f6c2f2SEnji Cooper```cpp 236828f6c2f2SEnji CooperInvokeArgument<N>(arg_1, arg_2, ..., arg_m) 236928f6c2f2SEnji Cooper``` 237028f6c2f2SEnji Cooper 237128f6c2f2SEnji Cooperwill invoke the `N`-th (0-based) argument the mock function receives, with 237228f6c2f2SEnji Cooper`arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is a function 237328f6c2f2SEnji Cooperpointer, a functor, or a callback. gMock handles them all. 237428f6c2f2SEnji Cooper 237528f6c2f2SEnji CooperWith that, you could write: 237628f6c2f2SEnji Cooper 237728f6c2f2SEnji Cooper```cpp 237828f6c2f2SEnji Cooperusing ::testing::_; 237928f6c2f2SEnji Cooperusing ::testing::InvokeArgument; 238028f6c2f2SEnji Cooper... 238128f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis(_, _)) 238228f6c2f2SEnji Cooper .WillOnce(InvokeArgument<1>(5)); 238328f6c2f2SEnji Cooper // Will execute callback->Run(5), where callback is the 238428f6c2f2SEnji Cooper // second argument DoThis() receives. 238528f6c2f2SEnji Cooper``` 238628f6c2f2SEnji Cooper 238728f6c2f2SEnji CooperWhat if the callable takes an argument by reference? No problem - just wrap it 238828f6c2f2SEnji Cooperinside `std::ref()`: 238928f6c2f2SEnji Cooper 239028f6c2f2SEnji Cooper```cpp 239128f6c2f2SEnji Cooper ... 239228f6c2f2SEnji Cooper MOCK_METHOD(bool, Bar, 239328f6c2f2SEnji Cooper ((ResultCallback2<bool, int, const Helper&>* callback)), 239428f6c2f2SEnji Cooper (override)); 239528f6c2f2SEnji Cooper ... 239628f6c2f2SEnji Cooper using ::testing::_; 239728f6c2f2SEnji Cooper using ::testing::InvokeArgument; 239828f6c2f2SEnji Cooper ... 239928f6c2f2SEnji Cooper MockFoo foo; 240028f6c2f2SEnji Cooper Helper helper; 240128f6c2f2SEnji Cooper ... 240228f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar(_)) 240328f6c2f2SEnji Cooper .WillOnce(InvokeArgument<0>(5, std::ref(helper))); 240428f6c2f2SEnji Cooper // std::ref(helper) guarantees that a reference to helper, not a copy of 240528f6c2f2SEnji Cooper // it, will be passed to the callback. 240628f6c2f2SEnji Cooper``` 240728f6c2f2SEnji Cooper 240828f6c2f2SEnji CooperWhat if the callable takes an argument by reference and we do **not** wrap the 240928f6c2f2SEnji Cooperargument in `std::ref()`? Then `InvokeArgument()` will *make a copy* of the 241028f6c2f2SEnji Cooperargument, and pass a *reference to the copy*, instead of a reference to the 241128f6c2f2SEnji Cooperoriginal value, to the callable. This is especially handy when the argument is a 241228f6c2f2SEnji Coopertemporary value: 241328f6c2f2SEnji Cooper 241428f6c2f2SEnji Cooper```cpp 241528f6c2f2SEnji Cooper ... 241628f6c2f2SEnji Cooper MOCK_METHOD(bool, DoThat, (bool (*f)(const double& x, const string& s)), 241728f6c2f2SEnji Cooper (override)); 241828f6c2f2SEnji Cooper ... 241928f6c2f2SEnji Cooper using ::testing::_; 242028f6c2f2SEnji Cooper using ::testing::InvokeArgument; 242128f6c2f2SEnji Cooper ... 242228f6c2f2SEnji Cooper MockFoo foo; 242328f6c2f2SEnji Cooper ... 242428f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThat(_)) 242528f6c2f2SEnji Cooper .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); 242628f6c2f2SEnji Cooper // Will execute (*f)(5.0, string("Hi")), where f is the function pointer 242728f6c2f2SEnji Cooper // DoThat() receives. Note that the values 5.0 and string("Hi") are 242828f6c2f2SEnji Cooper // temporary and dead once the EXPECT_CALL() statement finishes. Yet 242928f6c2f2SEnji Cooper // it's fine to perform this action later, since a copy of the values 243028f6c2f2SEnji Cooper // are kept inside the InvokeArgument action. 243128f6c2f2SEnji Cooper``` 243228f6c2f2SEnji Cooper 243328f6c2f2SEnji Cooper### Ignoring an Action's Result 243428f6c2f2SEnji Cooper 243528f6c2f2SEnji CooperSometimes you have an action that returns *something*, but you need an action 243628f6c2f2SEnji Cooperthat returns `void` (perhaps you want to use it in a mock function that returns 243728f6c2f2SEnji Cooper`void`, or perhaps it needs to be used in `DoAll()` and it's not the last in the 243828f6c2f2SEnji Cooperlist). `IgnoreResult()` lets you do that. For example: 243928f6c2f2SEnji Cooper 244028f6c2f2SEnji Cooper```cpp 244128f6c2f2SEnji Cooperusing ::testing::_; 244228f6c2f2SEnji Cooperusing ::testing::DoAll; 244328f6c2f2SEnji Cooperusing ::testing::IgnoreResult; 244428f6c2f2SEnji Cooperusing ::testing::Return; 244528f6c2f2SEnji Cooper 244628f6c2f2SEnji Cooperint Process(const MyData& data); 244728f6c2f2SEnji Cooperstring DoSomething(); 244828f6c2f2SEnji Cooper 244928f6c2f2SEnji Cooperclass MockFoo : public Foo { 245028f6c2f2SEnji Cooper public: 245128f6c2f2SEnji Cooper MOCK_METHOD(void, Abc, (const MyData& data), (override)); 245228f6c2f2SEnji Cooper MOCK_METHOD(bool, Xyz, (), (override)); 245328f6c2f2SEnji Cooper}; 245428f6c2f2SEnji Cooper 245528f6c2f2SEnji Cooper ... 245628f6c2f2SEnji Cooper MockFoo foo; 245728f6c2f2SEnji Cooper EXPECT_CALL(foo, Abc(_)) 245828f6c2f2SEnji Cooper // .WillOnce(Invoke(Process)); 245928f6c2f2SEnji Cooper // The above line won't compile as Process() returns int but Abc() needs 246028f6c2f2SEnji Cooper // to return void. 246128f6c2f2SEnji Cooper .WillOnce(IgnoreResult(Process)); 246228f6c2f2SEnji Cooper EXPECT_CALL(foo, Xyz()) 246328f6c2f2SEnji Cooper .WillOnce(DoAll(IgnoreResult(DoSomething), 246428f6c2f2SEnji Cooper // Ignores the string DoSomething() returns. 246528f6c2f2SEnji Cooper Return(true))); 246628f6c2f2SEnji Cooper``` 246728f6c2f2SEnji Cooper 246828f6c2f2SEnji CooperNote that you **cannot** use `IgnoreResult()` on an action that already returns 246928f6c2f2SEnji Cooper`void`. Doing so will lead to ugly compiler errors. 247028f6c2f2SEnji Cooper 247128f6c2f2SEnji Cooper### Selecting an Action's Arguments {#SelectingArgs} 247228f6c2f2SEnji Cooper 247328f6c2f2SEnji CooperSay you have a mock function `Foo()` that takes seven arguments, and you have a 247428f6c2f2SEnji Coopercustom action that you want to invoke when `Foo()` is called. Trouble is, the 247528f6c2f2SEnji Coopercustom action only wants three arguments: 247628f6c2f2SEnji Cooper 247728f6c2f2SEnji Cooper```cpp 247828f6c2f2SEnji Cooperusing ::testing::_; 247928f6c2f2SEnji Cooperusing ::testing::Invoke; 248028f6c2f2SEnji Cooper... 248128f6c2f2SEnji Cooper MOCK_METHOD(bool, Foo, 248228f6c2f2SEnji Cooper (bool visible, const string& name, int x, int y, 248328f6c2f2SEnji Cooper (const map<pair<int, int>>), double& weight, double min_weight, 248428f6c2f2SEnji Cooper double max_wight)); 248528f6c2f2SEnji Cooper... 248628f6c2f2SEnji Cooperbool IsVisibleInQuadrant1(bool visible, int x, int y) { 248728f6c2f2SEnji Cooper return visible && x >= 0 && y >= 0; 248828f6c2f2SEnji Cooper} 248928f6c2f2SEnji Cooper... 249028f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo) 249128f6c2f2SEnji Cooper .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( 249228f6c2f2SEnji Cooper``` 249328f6c2f2SEnji Cooper 249428f6c2f2SEnji CooperTo please the compiler God, you need to define an "adaptor" that has the same 249528f6c2f2SEnji Coopersignature as `Foo()` and calls the custom action with the right arguments: 249628f6c2f2SEnji Cooper 249728f6c2f2SEnji Cooper```cpp 249828f6c2f2SEnji Cooperusing ::testing::_; 249928f6c2f2SEnji Cooperusing ::testing::Invoke; 250028f6c2f2SEnji Cooper... 250128f6c2f2SEnji Cooperbool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, 250228f6c2f2SEnji Cooper const map<pair<int, int>, double>& weight, 250328f6c2f2SEnji Cooper double min_weight, double max_wight) { 250428f6c2f2SEnji Cooper return IsVisibleInQuadrant1(visible, x, y); 250528f6c2f2SEnji Cooper} 250628f6c2f2SEnji Cooper... 250728f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo) 250828f6c2f2SEnji Cooper .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. 250928f6c2f2SEnji Cooper``` 251028f6c2f2SEnji Cooper 251128f6c2f2SEnji CooperBut isn't this awkward? 251228f6c2f2SEnji Cooper 251328f6c2f2SEnji CoopergMock provides a generic *action adaptor*, so you can spend your time minding 251428f6c2f2SEnji Coopermore important business than writing your own adaptors. Here's the syntax: 251528f6c2f2SEnji Cooper 251628f6c2f2SEnji Cooper```cpp 251728f6c2f2SEnji CooperWithArgs<N1, N2, ..., Nk>(action) 251828f6c2f2SEnji Cooper``` 251928f6c2f2SEnji Cooper 252028f6c2f2SEnji Coopercreates an action that passes the arguments of the mock function at the given 252128f6c2f2SEnji Cooperindices (0-based) to the inner `action` and performs it. Using `WithArgs`, our 252228f6c2f2SEnji Cooperoriginal example can be written as: 252328f6c2f2SEnji Cooper 252428f6c2f2SEnji Cooper```cpp 252528f6c2f2SEnji Cooperusing ::testing::_; 252628f6c2f2SEnji Cooperusing ::testing::Invoke; 252728f6c2f2SEnji Cooperusing ::testing::WithArgs; 252828f6c2f2SEnji Cooper... 252928f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo) 253028f6c2f2SEnji Cooper .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); // No need to define your own adaptor. 253128f6c2f2SEnji Cooper``` 253228f6c2f2SEnji Cooper 253328f6c2f2SEnji CooperFor better readability, gMock also gives you: 253428f6c2f2SEnji Cooper 253528f6c2f2SEnji Cooper* `WithoutArgs(action)` when the inner `action` takes *no* argument, and 253628f6c2f2SEnji Cooper* `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes 253728f6c2f2SEnji Cooper *one* argument. 253828f6c2f2SEnji Cooper 253928f6c2f2SEnji CooperAs you may have realized, `InvokeWithoutArgs(...)` is just syntactic sugar for 254028f6c2f2SEnji Cooper`WithoutArgs(Invoke(...))`. 254128f6c2f2SEnji Cooper 254228f6c2f2SEnji CooperHere are more tips: 254328f6c2f2SEnji Cooper 254428f6c2f2SEnji Cooper* The inner action used in `WithArgs` and friends does not have to be 254528f6c2f2SEnji Cooper `Invoke()` -- it can be anything. 254628f6c2f2SEnji Cooper* You can repeat an argument in the argument list if necessary, e.g. 254728f6c2f2SEnji Cooper `WithArgs<2, 3, 3, 5>(...)`. 254828f6c2f2SEnji Cooper* You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. 254928f6c2f2SEnji Cooper* The types of the selected arguments do *not* have to match the signature of 255028f6c2f2SEnji Cooper the inner action exactly. It works as long as they can be implicitly 255128f6c2f2SEnji Cooper converted to the corresponding arguments of the inner action. For example, 255228f6c2f2SEnji Cooper if the 4-th argument of the mock function is an `int` and `my_action` takes 255328f6c2f2SEnji Cooper a `double`, `WithArg<4>(my_action)` will work. 255428f6c2f2SEnji Cooper 255528f6c2f2SEnji Cooper### Ignoring Arguments in Action Functions 255628f6c2f2SEnji Cooper 255728f6c2f2SEnji CooperThe [selecting-an-action's-arguments](#SelectingArgs) recipe showed us one way 255828f6c2f2SEnji Cooperto make a mock function and an action with incompatible argument lists fit 255928f6c2f2SEnji Coopertogether. The downside is that wrapping the action in `WithArgs<...>()` can get 256028f6c2f2SEnji Coopertedious for people writing the tests. 256128f6c2f2SEnji Cooper 256228f6c2f2SEnji CooperIf you are defining a function (or method, functor, lambda, callback) to be used 256328f6c2f2SEnji Cooperwith `Invoke*()`, and you are not interested in some of its arguments, an 256428f6c2f2SEnji Cooperalternative to `WithArgs` is to declare the uninteresting arguments as `Unused`. 256528f6c2f2SEnji CooperThis makes the definition less cluttered and less fragile in case the types of 256628f6c2f2SEnji Cooperthe uninteresting arguments change. It could also increase the chance the action 256728f6c2f2SEnji Cooperfunction can be reused. For example, given 256828f6c2f2SEnji Cooper 256928f6c2f2SEnji Cooper```cpp 257028f6c2f2SEnji Cooper public: 257128f6c2f2SEnji Cooper MOCK_METHOD(double, Foo, double(const string& label, double x, double y), 257228f6c2f2SEnji Cooper (override)); 257328f6c2f2SEnji Cooper MOCK_METHOD(double, Bar, (int index, double x, double y), (override)); 257428f6c2f2SEnji Cooper``` 257528f6c2f2SEnji Cooper 257628f6c2f2SEnji Cooperinstead of 257728f6c2f2SEnji Cooper 257828f6c2f2SEnji Cooper```cpp 257928f6c2f2SEnji Cooperusing ::testing::_; 258028f6c2f2SEnji Cooperusing ::testing::Invoke; 258128f6c2f2SEnji Cooper 258228f6c2f2SEnji Cooperdouble DistanceToOriginWithLabel(const string& label, double x, double y) { 258328f6c2f2SEnji Cooper return sqrt(x*x + y*y); 258428f6c2f2SEnji Cooper} 258528f6c2f2SEnji Cooperdouble DistanceToOriginWithIndex(int index, double x, double y) { 258628f6c2f2SEnji Cooper return sqrt(x*x + y*y); 258728f6c2f2SEnji Cooper} 258828f6c2f2SEnji Cooper... 258928f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo("abc", _, _)) 259028f6c2f2SEnji Cooper .WillOnce(Invoke(DistanceToOriginWithLabel)); 259128f6c2f2SEnji Cooper EXPECT_CALL(mock, Bar(5, _, _)) 259228f6c2f2SEnji Cooper .WillOnce(Invoke(DistanceToOriginWithIndex)); 259328f6c2f2SEnji Cooper``` 259428f6c2f2SEnji Cooper 259528f6c2f2SEnji Cooperyou could write 259628f6c2f2SEnji Cooper 259728f6c2f2SEnji Cooper```cpp 259828f6c2f2SEnji Cooperusing ::testing::_; 259928f6c2f2SEnji Cooperusing ::testing::Invoke; 260028f6c2f2SEnji Cooperusing ::testing::Unused; 260128f6c2f2SEnji Cooper 260228f6c2f2SEnji Cooperdouble DistanceToOrigin(Unused, double x, double y) { 260328f6c2f2SEnji Cooper return sqrt(x*x + y*y); 260428f6c2f2SEnji Cooper} 260528f6c2f2SEnji Cooper... 260628f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo("abc", _, _)) 260728f6c2f2SEnji Cooper .WillOnce(Invoke(DistanceToOrigin)); 260828f6c2f2SEnji Cooper EXPECT_CALL(mock, Bar(5, _, _)) 260928f6c2f2SEnji Cooper .WillOnce(Invoke(DistanceToOrigin)); 261028f6c2f2SEnji Cooper``` 261128f6c2f2SEnji Cooper 261228f6c2f2SEnji Cooper### Sharing Actions 261328f6c2f2SEnji Cooper 261428f6c2f2SEnji CooperJust like matchers, a gMock action object consists of a pointer to a ref-counted 261528f6c2f2SEnji Cooperimplementation object. Therefore copying actions is also allowed and very 261628f6c2f2SEnji Cooperefficient. When the last action that references the implementation object dies, 261728f6c2f2SEnji Cooperthe implementation object will be deleted. 261828f6c2f2SEnji Cooper 261928f6c2f2SEnji CooperIf you have some complex action that you want to use again and again, you may 262028f6c2f2SEnji Coopernot have to build it from scratch every time. If the action doesn't have an 262128f6c2f2SEnji Cooperinternal state (i.e. if it always does the same thing no matter how many times 262228f6c2f2SEnji Cooperit has been called), you can assign it to an action variable and use that 262328f6c2f2SEnji Coopervariable repeatedly. For example: 262428f6c2f2SEnji Cooper 262528f6c2f2SEnji Cooper```cpp 262628f6c2f2SEnji Cooperusing ::testing::Action; 262728f6c2f2SEnji Cooperusing ::testing::DoAll; 262828f6c2f2SEnji Cooperusing ::testing::Return; 262928f6c2f2SEnji Cooperusing ::testing::SetArgPointee; 263028f6c2f2SEnji Cooper... 263128f6c2f2SEnji Cooper Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5), 263228f6c2f2SEnji Cooper Return(true)); 263328f6c2f2SEnji Cooper ... use set_flag in .WillOnce() and .WillRepeatedly() ... 263428f6c2f2SEnji Cooper``` 263528f6c2f2SEnji Cooper 263628f6c2f2SEnji CooperHowever, if the action has its own state, you may be surprised if you share the 263728f6c2f2SEnji Cooperaction object. Suppose you have an action factory `IncrementCounter(init)` which 263828f6c2f2SEnji Coopercreates an action that increments and returns a counter whose initial value is 263928f6c2f2SEnji Cooper`init`, using two actions created from the same expression and using a shared 264028f6c2f2SEnji Cooperaction will exhibit different behaviors. Example: 264128f6c2f2SEnji Cooper 264228f6c2f2SEnji Cooper```cpp 264328f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis()) 264428f6c2f2SEnji Cooper .WillRepeatedly(IncrementCounter(0)); 264528f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThat()) 264628f6c2f2SEnji Cooper .WillRepeatedly(IncrementCounter(0)); 264728f6c2f2SEnji Cooper foo.DoThis(); // Returns 1. 264828f6c2f2SEnji Cooper foo.DoThis(); // Returns 2. 264928f6c2f2SEnji Cooper foo.DoThat(); // Returns 1 - DoThat() uses a different 265028f6c2f2SEnji Cooper // counter than DoThis()'s. 265128f6c2f2SEnji Cooper``` 265228f6c2f2SEnji Cooper 265328f6c2f2SEnji Cooperversus 265428f6c2f2SEnji Cooper 265528f6c2f2SEnji Cooper```cpp 265628f6c2f2SEnji Cooperusing ::testing::Action; 265728f6c2f2SEnji Cooper... 265828f6c2f2SEnji Cooper Action<int()> increment = IncrementCounter(0); 265928f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis()) 266028f6c2f2SEnji Cooper .WillRepeatedly(increment); 266128f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThat()) 266228f6c2f2SEnji Cooper .WillRepeatedly(increment); 266328f6c2f2SEnji Cooper foo.DoThis(); // Returns 1. 266428f6c2f2SEnji Cooper foo.DoThis(); // Returns 2. 266528f6c2f2SEnji Cooper foo.DoThat(); // Returns 3 - the counter is shared. 266628f6c2f2SEnji Cooper``` 266728f6c2f2SEnji Cooper 266828f6c2f2SEnji Cooper### Testing Asynchronous Behavior 266928f6c2f2SEnji Cooper 267028f6c2f2SEnji CooperOne oft-encountered problem with gMock is that it can be hard to test 267128f6c2f2SEnji Cooperasynchronous behavior. Suppose you had a `EventQueue` class that you wanted to 267228f6c2f2SEnji Coopertest, and you created a separate `EventDispatcher` interface so that you could 267328f6c2f2SEnji Coopereasily mock it out. However, the implementation of the class fired all the 267428f6c2f2SEnji Cooperevents on a background thread, which made test timings difficult. You could just 267528f6c2f2SEnji Cooperinsert `sleep()` statements and hope for the best, but that makes your test 267628f6c2f2SEnji Cooperbehavior nondeterministic. A better way is to use gMock actions and 267728f6c2f2SEnji Cooper`Notification` objects to force your asynchronous test to behave synchronously. 267828f6c2f2SEnji Cooper 267928f6c2f2SEnji Cooper```cpp 268028f6c2f2SEnji Cooperclass MockEventDispatcher : public EventDispatcher { 268128f6c2f2SEnji Cooper MOCK_METHOD(bool, DispatchEvent, (int32), (override)); 268228f6c2f2SEnji Cooper}; 268328f6c2f2SEnji Cooper 268428f6c2f2SEnji CooperTEST(EventQueueTest, EnqueueEventTest) { 268528f6c2f2SEnji Cooper MockEventDispatcher mock_event_dispatcher; 268628f6c2f2SEnji Cooper EventQueue event_queue(&mock_event_dispatcher); 268728f6c2f2SEnji Cooper 268828f6c2f2SEnji Cooper const int32 kEventId = 321; 268928f6c2f2SEnji Cooper absl::Notification done; 269028f6c2f2SEnji Cooper EXPECT_CALL(mock_event_dispatcher, DispatchEvent(kEventId)) 269128f6c2f2SEnji Cooper .WillOnce([&done] { done.Notify(); }); 269228f6c2f2SEnji Cooper 269328f6c2f2SEnji Cooper event_queue.EnqueueEvent(kEventId); 269428f6c2f2SEnji Cooper done.WaitForNotification(); 269528f6c2f2SEnji Cooper} 269628f6c2f2SEnji Cooper``` 269728f6c2f2SEnji Cooper 269828f6c2f2SEnji CooperIn the example above, we set our normal gMock expectations, but then add an 269928f6c2f2SEnji Cooperadditional action to notify the `Notification` object. Now we can just call 270028f6c2f2SEnji Cooper`Notification::WaitForNotification()` in the main thread to wait for the 270128f6c2f2SEnji Cooperasynchronous call to finish. After that, our test suite is complete and we can 270228f6c2f2SEnji Coopersafely exit. 270328f6c2f2SEnji Cooper 270428f6c2f2SEnji Cooper{: .callout .note} 270528f6c2f2SEnji CooperNote: this example has a downside: namely, if the expectation is not satisfied, 270628f6c2f2SEnji Cooperour test will run forever. It will eventually time-out and fail, but it will 270728f6c2f2SEnji Coopertake longer and be slightly harder to debug. To alleviate this problem, you can 270828f6c2f2SEnji Cooperuse `WaitForNotificationWithTimeout(ms)` instead of `WaitForNotification()`. 270928f6c2f2SEnji Cooper 271028f6c2f2SEnji Cooper## Misc Recipes on Using gMock 271128f6c2f2SEnji Cooper 271228f6c2f2SEnji Cooper### Mocking Methods That Use Move-Only Types 271328f6c2f2SEnji Cooper 271428f6c2f2SEnji CooperC++11 introduced *move-only types*. A move-only-typed value can be moved from 271528f6c2f2SEnji Cooperone object to another, but cannot be copied. `std::unique_ptr<T>` is probably 271628f6c2f2SEnji Cooperthe most commonly used move-only type. 271728f6c2f2SEnji Cooper 271828f6c2f2SEnji CooperMocking a method that takes and/or returns move-only types presents some 271928f6c2f2SEnji Cooperchallenges, but nothing insurmountable. This recipe shows you how you can do it. 272028f6c2f2SEnji CooperNote that the support for move-only method arguments was only introduced to 272128f6c2f2SEnji CoopergMock in April 2017; in older code, you may find more complex 272228f6c2f2SEnji Cooper[workarounds](#LegacyMoveOnly) for lack of this feature. 272328f6c2f2SEnji Cooper 272428f6c2f2SEnji CooperLet’s say we are working on a fictional project that lets one post and share 272528f6c2f2SEnji Coopersnippets called “buzzes”. Your code uses these types: 272628f6c2f2SEnji Cooper 272728f6c2f2SEnji Cooper```cpp 272828f6c2f2SEnji Cooperenum class AccessLevel { kInternal, kPublic }; 272928f6c2f2SEnji Cooper 273028f6c2f2SEnji Cooperclass Buzz { 273128f6c2f2SEnji Cooper public: 273228f6c2f2SEnji Cooper explicit Buzz(AccessLevel access) { ... } 273328f6c2f2SEnji Cooper ... 273428f6c2f2SEnji Cooper}; 273528f6c2f2SEnji Cooper 273628f6c2f2SEnji Cooperclass Buzzer { 273728f6c2f2SEnji Cooper public: 273828f6c2f2SEnji Cooper virtual ~Buzzer() {} 273928f6c2f2SEnji Cooper virtual std::unique_ptr<Buzz> MakeBuzz(StringPiece text) = 0; 274028f6c2f2SEnji Cooper virtual bool ShareBuzz(std::unique_ptr<Buzz> buzz, int64_t timestamp) = 0; 274128f6c2f2SEnji Cooper ... 274228f6c2f2SEnji Cooper}; 274328f6c2f2SEnji Cooper``` 274428f6c2f2SEnji Cooper 274528f6c2f2SEnji CooperA `Buzz` object represents a snippet being posted. A class that implements the 274628f6c2f2SEnji Cooper`Buzzer` interface is capable of creating and sharing `Buzz`es. Methods in 274728f6c2f2SEnji Cooper`Buzzer` may return a `unique_ptr<Buzz>` or take a `unique_ptr<Buzz>`. Now we 274828f6c2f2SEnji Cooperneed to mock `Buzzer` in our tests. 274928f6c2f2SEnji Cooper 275028f6c2f2SEnji CooperTo mock a method that accepts or returns move-only types, you just use the 275128f6c2f2SEnji Cooperfamiliar `MOCK_METHOD` syntax as usual: 275228f6c2f2SEnji Cooper 275328f6c2f2SEnji Cooper```cpp 275428f6c2f2SEnji Cooperclass MockBuzzer : public Buzzer { 275528f6c2f2SEnji Cooper public: 275628f6c2f2SEnji Cooper MOCK_METHOD(std::unique_ptr<Buzz>, MakeBuzz, (StringPiece text), (override)); 275728f6c2f2SEnji Cooper MOCK_METHOD(bool, ShareBuzz, (std::unique_ptr<Buzz> buzz, int64_t timestamp), 275828f6c2f2SEnji Cooper (override)); 275928f6c2f2SEnji Cooper}; 276028f6c2f2SEnji Cooper``` 276128f6c2f2SEnji Cooper 276228f6c2f2SEnji CooperNow that we have the mock class defined, we can use it in tests. In the 276328f6c2f2SEnji Cooperfollowing code examples, we assume that we have defined a `MockBuzzer` object 276428f6c2f2SEnji Coopernamed `mock_buzzer_`: 276528f6c2f2SEnji Cooper 276628f6c2f2SEnji Cooper```cpp 276728f6c2f2SEnji Cooper MockBuzzer mock_buzzer_; 276828f6c2f2SEnji Cooper``` 276928f6c2f2SEnji Cooper 277028f6c2f2SEnji CooperFirst let’s see how we can set expectations on the `MakeBuzz()` method, which 277128f6c2f2SEnji Cooperreturns a `unique_ptr<Buzz>`. 277228f6c2f2SEnji Cooper 277328f6c2f2SEnji CooperAs usual, if you set an expectation without an action (i.e. the `.WillOnce()` or 277428f6c2f2SEnji Cooper`.WillRepeatedly()` clause), when that expectation fires, the default action for 277528f6c2f2SEnji Cooperthat method will be taken. Since `unique_ptr<>` has a default constructor that 277628f6c2f2SEnji Cooperreturns a null `unique_ptr`, that’s what you’ll get if you don’t specify an 277728f6c2f2SEnji Cooperaction: 277828f6c2f2SEnji Cooper 277928f6c2f2SEnji Cooper```cpp 278028f6c2f2SEnji Cooperusing ::testing::IsNull; 278128f6c2f2SEnji Cooper... 278228f6c2f2SEnji Cooper // Use the default action. 278328f6c2f2SEnji Cooper EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); 278428f6c2f2SEnji Cooper 278528f6c2f2SEnji Cooper // Triggers the previous EXPECT_CALL. 278628f6c2f2SEnji Cooper EXPECT_THAT(mock_buzzer_.MakeBuzz("hello"), IsNull()); 278728f6c2f2SEnji Cooper``` 278828f6c2f2SEnji Cooper 278928f6c2f2SEnji CooperIf you are not happy with the default action, you can tweak it as usual; see 279028f6c2f2SEnji Cooper[Setting Default Actions](#OnCall). 279128f6c2f2SEnji Cooper 279228f6c2f2SEnji CooperIf you just need to return a move-only value, you can use it in combination with 279328f6c2f2SEnji Cooper`WillOnce`. For example: 279428f6c2f2SEnji Cooper 279528f6c2f2SEnji Cooper```cpp 279628f6c2f2SEnji Cooper EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")) 279728f6c2f2SEnji Cooper .WillOnce(Return(std::make_unique<Buzz>(AccessLevel::kInternal))); 279828f6c2f2SEnji Cooper EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("hello")); 279928f6c2f2SEnji Cooper``` 280028f6c2f2SEnji Cooper 280128f6c2f2SEnji CooperQuiz time! What do you think will happen if a `Return` action is performed more 280228f6c2f2SEnji Cooperthan once (e.g. you write `... .WillRepeatedly(Return(std::move(...)));`)? Come 280328f6c2f2SEnji Cooperthink of it, after the first time the action runs, the source value will be 280428f6c2f2SEnji Cooperconsumed (since it’s a move-only value), so the next time around, there’s no 280528f6c2f2SEnji Coopervalue to move from -- you’ll get a run-time error that `Return(std::move(...))` 280628f6c2f2SEnji Coopercan only be run once. 280728f6c2f2SEnji Cooper 280828f6c2f2SEnji CooperIf you need your mock method to do more than just moving a pre-defined value, 280928f6c2f2SEnji Cooperremember that you can always use a lambda or a callable object, which can do 281028f6c2f2SEnji Cooperpretty much anything you want: 281128f6c2f2SEnji Cooper 281228f6c2f2SEnji Cooper```cpp 281328f6c2f2SEnji Cooper EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) 281428f6c2f2SEnji Cooper .WillRepeatedly([](StringPiece text) { 281528f6c2f2SEnji Cooper return std::make_unique<Buzz>(AccessLevel::kInternal); 281628f6c2f2SEnji Cooper }); 281728f6c2f2SEnji Cooper 281828f6c2f2SEnji Cooper EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); 281928f6c2f2SEnji Cooper EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); 282028f6c2f2SEnji Cooper``` 282128f6c2f2SEnji Cooper 282228f6c2f2SEnji CooperEvery time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created 282328f6c2f2SEnji Cooperand returned. You cannot do this with `Return(std::make_unique<...>(...))`. 282428f6c2f2SEnji Cooper 282528f6c2f2SEnji CooperThat covers returning move-only values; but how do we work with methods 282628f6c2f2SEnji Cooperaccepting move-only arguments? The answer is that they work normally, although 282728f6c2f2SEnji Coopersome actions will not compile when any of method's arguments are move-only. You 282828f6c2f2SEnji Coopercan always use `Return`, or a [lambda or functor](#FunctionsAsActions): 282928f6c2f2SEnji Cooper 283028f6c2f2SEnji Cooper```cpp 283128f6c2f2SEnji Cooper using ::testing::Unused; 283228f6c2f2SEnji Cooper 283328f6c2f2SEnji Cooper EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true)); 283428f6c2f2SEnji Cooper EXPECT_TRUE(mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal)), 283528f6c2f2SEnji Cooper 0); 283628f6c2f2SEnji Cooper 283728f6c2f2SEnji Cooper EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce( 283828f6c2f2SEnji Cooper [](std::unique_ptr<Buzz> buzz, Unused) { return buzz != nullptr; }); 283928f6c2f2SEnji Cooper EXPECT_FALSE(mock_buzzer_.ShareBuzz(nullptr, 0)); 284028f6c2f2SEnji Cooper``` 284128f6c2f2SEnji Cooper 284228f6c2f2SEnji CooperMany built-in actions (`WithArgs`, `WithoutArgs`,`DeleteArg`, `SaveArg`, ...) 284328f6c2f2SEnji Coopercould in principle support move-only arguments, but the support for this is not 284428f6c2f2SEnji Cooperimplemented yet. If this is blocking you, please file a bug. 284528f6c2f2SEnji Cooper 284628f6c2f2SEnji CooperA few actions (e.g. `DoAll`) copy their arguments internally, so they can never 284728f6c2f2SEnji Cooperwork with non-copyable objects; you'll have to use functors instead. 284828f6c2f2SEnji Cooper 284928f6c2f2SEnji Cooper#### Legacy workarounds for move-only types {#LegacyMoveOnly} 285028f6c2f2SEnji Cooper 285128f6c2f2SEnji CooperSupport for move-only function arguments was only introduced to gMock in April 285228f6c2f2SEnji Cooperof 2017. In older code, you may encounter the following workaround for the lack 285328f6c2f2SEnji Cooperof this feature (it is no longer necessary - we're including it just for 285428f6c2f2SEnji Cooperreference): 285528f6c2f2SEnji Cooper 285628f6c2f2SEnji Cooper```cpp 285728f6c2f2SEnji Cooperclass MockBuzzer : public Buzzer { 285828f6c2f2SEnji Cooper public: 285928f6c2f2SEnji Cooper MOCK_METHOD(bool, DoShareBuzz, (Buzz* buzz, Time timestamp)); 286028f6c2f2SEnji Cooper bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) override { 286128f6c2f2SEnji Cooper return DoShareBuzz(buzz.get(), timestamp); 286228f6c2f2SEnji Cooper } 286328f6c2f2SEnji Cooper}; 286428f6c2f2SEnji Cooper``` 286528f6c2f2SEnji Cooper 286628f6c2f2SEnji CooperThe trick is to delegate the `ShareBuzz()` method to a mock method (let’s call 286728f6c2f2SEnji Cooperit `DoShareBuzz()`) that does not take move-only parameters. Then, instead of 286828f6c2f2SEnji Coopersetting expectations on `ShareBuzz()`, you set them on the `DoShareBuzz()` mock 286928f6c2f2SEnji Coopermethod: 287028f6c2f2SEnji Cooper 287128f6c2f2SEnji Cooper```cpp 287228f6c2f2SEnji Cooper MockBuzzer mock_buzzer_; 287328f6c2f2SEnji Cooper EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); 287428f6c2f2SEnji Cooper 287528f6c2f2SEnji Cooper // When one calls ShareBuzz() on the MockBuzzer like this, the call is 287628f6c2f2SEnji Cooper // forwarded to DoShareBuzz(), which is mocked. Therefore this statement 287728f6c2f2SEnji Cooper // will trigger the above EXPECT_CALL. 287828f6c2f2SEnji Cooper mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal), 0); 287928f6c2f2SEnji Cooper``` 288028f6c2f2SEnji Cooper 288128f6c2f2SEnji Cooper### Making the Compilation Faster 288228f6c2f2SEnji Cooper 288328f6c2f2SEnji CooperBelieve it or not, the *vast majority* of the time spent on compiling a mock 288428f6c2f2SEnji Cooperclass is in generating its constructor and destructor, as they perform 288528f6c2f2SEnji Coopernon-trivial tasks (e.g. verification of the expectations). What's more, mock 288628f6c2f2SEnji Coopermethods with different signatures have different types and thus their 288728f6c2f2SEnji Cooperconstructors/destructors need to be generated by the compiler separately. As a 288828f6c2f2SEnji Cooperresult, if you mock many different types of methods, compiling your mock class 288928f6c2f2SEnji Coopercan get really slow. 289028f6c2f2SEnji Cooper 289128f6c2f2SEnji CooperIf you are experiencing slow compilation, you can move the definition of your 289228f6c2f2SEnji Coopermock class' constructor and destructor out of the class body and into a `.cc` 289328f6c2f2SEnji Cooperfile. This way, even if you `#include` your mock class in N files, the compiler 289428f6c2f2SEnji Cooperonly needs to generate its constructor and destructor once, resulting in a much 289528f6c2f2SEnji Cooperfaster compilation. 289628f6c2f2SEnji Cooper 289728f6c2f2SEnji CooperLet's illustrate the idea using an example. Here's the definition of a mock 289828f6c2f2SEnji Cooperclass before applying this recipe: 289928f6c2f2SEnji Cooper 290028f6c2f2SEnji Cooper```cpp 290128f6c2f2SEnji Cooper// File mock_foo.h. 290228f6c2f2SEnji Cooper... 290328f6c2f2SEnji Cooperclass MockFoo : public Foo { 290428f6c2f2SEnji Cooper public: 290528f6c2f2SEnji Cooper // Since we don't declare the constructor or the destructor, 290628f6c2f2SEnji Cooper // the compiler will generate them in every translation unit 290728f6c2f2SEnji Cooper // where this mock class is used. 290828f6c2f2SEnji Cooper 290928f6c2f2SEnji Cooper MOCK_METHOD(int, DoThis, (), (override)); 291028f6c2f2SEnji Cooper MOCK_METHOD(bool, DoThat, (const char* str), (override)); 291128f6c2f2SEnji Cooper ... more mock methods ... 291228f6c2f2SEnji Cooper}; 291328f6c2f2SEnji Cooper``` 291428f6c2f2SEnji Cooper 291528f6c2f2SEnji CooperAfter the change, it would look like: 291628f6c2f2SEnji Cooper 291728f6c2f2SEnji Cooper```cpp 291828f6c2f2SEnji Cooper// File mock_foo.h. 291928f6c2f2SEnji Cooper... 292028f6c2f2SEnji Cooperclass MockFoo : public Foo { 292128f6c2f2SEnji Cooper public: 292228f6c2f2SEnji Cooper // The constructor and destructor are declared, but not defined, here. 292328f6c2f2SEnji Cooper MockFoo(); 292428f6c2f2SEnji Cooper virtual ~MockFoo(); 292528f6c2f2SEnji Cooper 292628f6c2f2SEnji Cooper MOCK_METHOD(int, DoThis, (), (override)); 292728f6c2f2SEnji Cooper MOCK_METHOD(bool, DoThat, (const char* str), (override)); 292828f6c2f2SEnji Cooper ... more mock methods ... 292928f6c2f2SEnji Cooper}; 293028f6c2f2SEnji Cooper``` 293128f6c2f2SEnji Cooper 293228f6c2f2SEnji Cooperand 293328f6c2f2SEnji Cooper 293428f6c2f2SEnji Cooper```cpp 293528f6c2f2SEnji Cooper// File mock_foo.cc. 293628f6c2f2SEnji Cooper#include "path/to/mock_foo.h" 293728f6c2f2SEnji Cooper 293828f6c2f2SEnji Cooper// The definitions may appear trivial, but the functions actually do a 293928f6c2f2SEnji Cooper// lot of things through the constructors/destructors of the member 294028f6c2f2SEnji Cooper// variables used to implement the mock methods. 294128f6c2f2SEnji CooperMockFoo::MockFoo() {} 294228f6c2f2SEnji CooperMockFoo::~MockFoo() {} 294328f6c2f2SEnji Cooper``` 294428f6c2f2SEnji Cooper 294528f6c2f2SEnji Cooper### Forcing a Verification 294628f6c2f2SEnji Cooper 294728f6c2f2SEnji CooperWhen it's being destroyed, your friendly mock object will automatically verify 294828f6c2f2SEnji Cooperthat all expectations on it have been satisfied, and will generate googletest 294928f6c2f2SEnji Cooperfailures if not. This is convenient as it leaves you with one less thing to 295028f6c2f2SEnji Cooperworry about. That is, unless you are not sure if your mock object will be 295128f6c2f2SEnji Cooperdestroyed. 295228f6c2f2SEnji Cooper 295328f6c2f2SEnji CooperHow could it be that your mock object won't eventually be destroyed? Well, it 295428f6c2f2SEnji Coopermight be created on the heap and owned by the code you are testing. Suppose 295528f6c2f2SEnji Cooperthere's a bug in that code and it doesn't delete the mock object properly - you 295628f6c2f2SEnji Coopercould end up with a passing test when there's actually a bug. 295728f6c2f2SEnji Cooper 295828f6c2f2SEnji CooperUsing a heap checker is a good idea and can alleviate the concern, but its 295928f6c2f2SEnji Cooperimplementation is not 100% reliable. So, sometimes you do want to *force* gMock 296028f6c2f2SEnji Cooperto verify a mock object before it is (hopefully) destructed. You can do this 296128f6c2f2SEnji Cooperwith `Mock::VerifyAndClearExpectations(&mock_object)`: 296228f6c2f2SEnji Cooper 296328f6c2f2SEnji Cooper```cpp 296428f6c2f2SEnji CooperTEST(MyServerTest, ProcessesRequest) { 296528f6c2f2SEnji Cooper using ::testing::Mock; 296628f6c2f2SEnji Cooper 296728f6c2f2SEnji Cooper MockFoo* const foo = new MockFoo; 296828f6c2f2SEnji Cooper EXPECT_CALL(*foo, ...)...; 296928f6c2f2SEnji Cooper // ... other expectations ... 297028f6c2f2SEnji Cooper 297128f6c2f2SEnji Cooper // server now owns foo. 297228f6c2f2SEnji Cooper MyServer server(foo); 297328f6c2f2SEnji Cooper server.ProcessRequest(...); 297428f6c2f2SEnji Cooper 297528f6c2f2SEnji Cooper // In case that server's destructor will forget to delete foo, 297628f6c2f2SEnji Cooper // this will verify the expectations anyway. 297728f6c2f2SEnji Cooper Mock::VerifyAndClearExpectations(foo); 297828f6c2f2SEnji Cooper} // server is destroyed when it goes out of scope here. 297928f6c2f2SEnji Cooper``` 298028f6c2f2SEnji Cooper 298128f6c2f2SEnji Cooper{: .callout .tip} 298228f6c2f2SEnji Cooper**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a `bool` to 298328f6c2f2SEnji Cooperindicate whether the verification was successful (`true` for yes), so you can 298428f6c2f2SEnji Cooperwrap that function call inside a `ASSERT_TRUE()` if there is no point going 298528f6c2f2SEnji Cooperfurther when the verification has failed. 298628f6c2f2SEnji Cooper 298728f6c2f2SEnji CooperDo not set new expectations after verifying and clearing a mock after its use. 298828f6c2f2SEnji CooperSetting expectations after code that exercises the mock has undefined behavior. 298928f6c2f2SEnji CooperSee [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more 299028f6c2f2SEnji Cooperinformation. 299128f6c2f2SEnji Cooper 299228f6c2f2SEnji Cooper### Using Checkpoints {#UsingCheckPoints} 299328f6c2f2SEnji Cooper 299428f6c2f2SEnji CooperSometimes you might want to test a mock object's behavior in phases whose sizes 299528f6c2f2SEnji Cooperare each manageable, or you might want to set more detailed expectations about 299628f6c2f2SEnji Cooperwhich API calls invoke which mock functions. 299728f6c2f2SEnji Cooper 299828f6c2f2SEnji CooperA technique you can use is to put the expectations in a sequence and insert 299928f6c2f2SEnji Coopercalls to a dummy "checkpoint" function at specific places. Then you can verify 300028f6c2f2SEnji Cooperthat the mock function calls do happen at the right time. For example, if you 300128f6c2f2SEnji Cooperare exercising the code: 300228f6c2f2SEnji Cooper 300328f6c2f2SEnji Cooper```cpp 300428f6c2f2SEnji Cooper Foo(1); 300528f6c2f2SEnji Cooper Foo(2); 300628f6c2f2SEnji Cooper Foo(3); 300728f6c2f2SEnji Cooper``` 300828f6c2f2SEnji Cooper 300928f6c2f2SEnji Cooperand want to verify that `Foo(1)` and `Foo(3)` both invoke `mock.Bar("a")`, but 301028f6c2f2SEnji Cooper`Foo(2)` doesn't invoke anything, you can write: 301128f6c2f2SEnji Cooper 301228f6c2f2SEnji Cooper```cpp 301328f6c2f2SEnji Cooperusing ::testing::MockFunction; 301428f6c2f2SEnji Cooper 301528f6c2f2SEnji CooperTEST(FooTest, InvokesBarCorrectly) { 301628f6c2f2SEnji Cooper MyMock mock; 301728f6c2f2SEnji Cooper // Class MockFunction<F> has exactly one mock method. It is named 301828f6c2f2SEnji Cooper // Call() and has type F. 301928f6c2f2SEnji Cooper MockFunction<void(string check_point_name)> check; 302028f6c2f2SEnji Cooper { 302128f6c2f2SEnji Cooper InSequence s; 302228f6c2f2SEnji Cooper 302328f6c2f2SEnji Cooper EXPECT_CALL(mock, Bar("a")); 302428f6c2f2SEnji Cooper EXPECT_CALL(check, Call("1")); 302528f6c2f2SEnji Cooper EXPECT_CALL(check, Call("2")); 302628f6c2f2SEnji Cooper EXPECT_CALL(mock, Bar("a")); 302728f6c2f2SEnji Cooper } 302828f6c2f2SEnji Cooper Foo(1); 302928f6c2f2SEnji Cooper check.Call("1"); 303028f6c2f2SEnji Cooper Foo(2); 303128f6c2f2SEnji Cooper check.Call("2"); 303228f6c2f2SEnji Cooper Foo(3); 303328f6c2f2SEnji Cooper} 303428f6c2f2SEnji Cooper``` 303528f6c2f2SEnji Cooper 303628f6c2f2SEnji CooperThe expectation spec says that the first `Bar("a")` call must happen before 303728f6c2f2SEnji Coopercheckpoint "1", the second `Bar("a")` call must happen after checkpoint "2", and 303828f6c2f2SEnji Coopernothing should happen between the two checkpoints. The explicit checkpoints make 303928f6c2f2SEnji Cooperit clear which `Bar("a")` is called by which call to `Foo()`. 304028f6c2f2SEnji Cooper 304128f6c2f2SEnji Cooper### Mocking Destructors 304228f6c2f2SEnji Cooper 304328f6c2f2SEnji CooperSometimes you want to make sure a mock object is destructed at the right time, 304428f6c2f2SEnji Coopere.g. after `bar->A()` is called but before `bar->B()` is called. We already know 304528f6c2f2SEnji Cooperthat you can specify constraints on the [order](#OrderedCalls) of mock function 304628f6c2f2SEnji Coopercalls, so all we need to do is to mock the destructor of the mock function. 304728f6c2f2SEnji Cooper 304828f6c2f2SEnji CooperThis sounds simple, except for one problem: a destructor is a special function 304928f6c2f2SEnji Cooperwith special syntax and special semantics, and the `MOCK_METHOD` macro doesn't 305028f6c2f2SEnji Cooperwork for it: 305128f6c2f2SEnji Cooper 305228f6c2f2SEnji Cooper```cpp 305328f6c2f2SEnji CooperMOCK_METHOD(void, ~MockFoo, ()); // Won't compile! 305428f6c2f2SEnji Cooper``` 305528f6c2f2SEnji Cooper 305628f6c2f2SEnji CooperThe good news is that you can use a simple pattern to achieve the same effect. 305728f6c2f2SEnji CooperFirst, add a mock function `Die()` to your mock class and call it in the 305828f6c2f2SEnji Cooperdestructor, like this: 305928f6c2f2SEnji Cooper 306028f6c2f2SEnji Cooper```cpp 306128f6c2f2SEnji Cooperclass MockFoo : public Foo { 306228f6c2f2SEnji Cooper ... 306328f6c2f2SEnji Cooper // Add the following two lines to the mock class. 306428f6c2f2SEnji Cooper MOCK_METHOD(void, Die, ()); 306528f6c2f2SEnji Cooper ~MockFoo() override { Die(); } 306628f6c2f2SEnji Cooper}; 306728f6c2f2SEnji Cooper``` 306828f6c2f2SEnji Cooper 306928f6c2f2SEnji Cooper(If the name `Die()` clashes with an existing symbol, choose another name.) Now, 307028f6c2f2SEnji Cooperwe have translated the problem of testing when a `MockFoo` object dies to 307128f6c2f2SEnji Coopertesting when its `Die()` method is called: 307228f6c2f2SEnji Cooper 307328f6c2f2SEnji Cooper```cpp 307428f6c2f2SEnji Cooper MockFoo* foo = new MockFoo; 307528f6c2f2SEnji Cooper MockBar* bar = new MockBar; 307628f6c2f2SEnji Cooper ... 307728f6c2f2SEnji Cooper { 307828f6c2f2SEnji Cooper InSequence s; 307928f6c2f2SEnji Cooper 308028f6c2f2SEnji Cooper // Expects *foo to die after bar->A() and before bar->B(). 308128f6c2f2SEnji Cooper EXPECT_CALL(*bar, A()); 308228f6c2f2SEnji Cooper EXPECT_CALL(*foo, Die()); 308328f6c2f2SEnji Cooper EXPECT_CALL(*bar, B()); 308428f6c2f2SEnji Cooper } 308528f6c2f2SEnji Cooper``` 308628f6c2f2SEnji Cooper 308728f6c2f2SEnji CooperAnd that's that. 308828f6c2f2SEnji Cooper 308928f6c2f2SEnji Cooper### Using gMock and Threads {#UsingThreads} 309028f6c2f2SEnji Cooper 309128f6c2f2SEnji CooperIn a **unit** test, it's best if you could isolate and test a piece of code in a 309228f6c2f2SEnji Coopersingle-threaded context. That avoids race conditions and dead locks, and makes 309328f6c2f2SEnji Cooperdebugging your test much easier. 309428f6c2f2SEnji Cooper 309528f6c2f2SEnji CooperYet most programs are multi-threaded, and sometimes to test something we need to 309628f6c2f2SEnji Cooperpound on it from more than one thread. gMock works for this purpose too. 309728f6c2f2SEnji Cooper 309828f6c2f2SEnji CooperRemember the steps for using a mock: 309928f6c2f2SEnji Cooper 310028f6c2f2SEnji Cooper1. Create a mock object `foo`. 310128f6c2f2SEnji Cooper2. Set its default actions and expectations using `ON_CALL()` and 310228f6c2f2SEnji Cooper `EXPECT_CALL()`. 310328f6c2f2SEnji Cooper3. The code under test calls methods of `foo`. 310428f6c2f2SEnji Cooper4. Optionally, verify and reset the mock. 310528f6c2f2SEnji Cooper5. Destroy the mock yourself, or let the code under test destroy it. The 310628f6c2f2SEnji Cooper destructor will automatically verify it. 310728f6c2f2SEnji Cooper 310828f6c2f2SEnji CooperIf you follow the following simple rules, your mocks and threads can live 310928f6c2f2SEnji Cooperhappily together: 311028f6c2f2SEnji Cooper 311128f6c2f2SEnji Cooper* Execute your *test code* (as opposed to the code being tested) in *one* 311228f6c2f2SEnji Cooper thread. This makes your test easy to follow. 311328f6c2f2SEnji Cooper* Obviously, you can do step #1 without locking. 311428f6c2f2SEnji Cooper* When doing step #2 and #5, make sure no other thread is accessing `foo`. 311528f6c2f2SEnji Cooper Obvious too, huh? 311628f6c2f2SEnji Cooper* #3 and #4 can be done either in one thread or in multiple threads - anyway 311728f6c2f2SEnji Cooper you want. gMock takes care of the locking, so you don't have to do any - 311828f6c2f2SEnji Cooper unless required by your test logic. 311928f6c2f2SEnji Cooper 312028f6c2f2SEnji CooperIf you violate the rules (for example, if you set expectations on a mock while 312128f6c2f2SEnji Cooperanother thread is calling its methods), you get undefined behavior. That's not 312228f6c2f2SEnji Cooperfun, so don't do it. 312328f6c2f2SEnji Cooper 312428f6c2f2SEnji CoopergMock guarantees that the action for a mock function is done in the same thread 312528f6c2f2SEnji Cooperthat called the mock function. For example, in 312628f6c2f2SEnji Cooper 312728f6c2f2SEnji Cooper```cpp 312828f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo(1)) 312928f6c2f2SEnji Cooper .WillOnce(action1); 313028f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo(2)) 313128f6c2f2SEnji Cooper .WillOnce(action2); 313228f6c2f2SEnji Cooper``` 313328f6c2f2SEnji Cooper 313428f6c2f2SEnji Cooperif `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, gMock will 313528f6c2f2SEnji Cooperexecute `action1` in thread 1 and `action2` in thread 2. 313628f6c2f2SEnji Cooper 313728f6c2f2SEnji CoopergMock does *not* impose a sequence on actions performed in different threads 313828f6c2f2SEnji Cooper(doing so may create deadlocks as the actions may need to cooperate). This means 313928f6c2f2SEnji Cooperthat the execution of `action1` and `action2` in the above example *may* 314028f6c2f2SEnji Cooperinterleave. If this is a problem, you should add proper synchronization logic to 314128f6c2f2SEnji Cooper`action1` and `action2` to make the test thread-safe. 314228f6c2f2SEnji Cooper 314328f6c2f2SEnji CooperAlso, remember that `DefaultValue<T>` is a global resource that potentially 314428f6c2f2SEnji Cooperaffects *all* living mock objects in your program. Naturally, you won't want to 314528f6c2f2SEnji Coopermess with it from multiple threads or when there still are mocks in action. 314628f6c2f2SEnji Cooper 314728f6c2f2SEnji Cooper### Controlling How Much Information gMock Prints 314828f6c2f2SEnji Cooper 314928f6c2f2SEnji CooperWhen gMock sees something that has the potential of being an error (e.g. a mock 315028f6c2f2SEnji Cooperfunction with no expectation is called, a.k.a. an uninteresting call, which is 315128f6c2f2SEnji Cooperallowed but perhaps you forgot to explicitly ban the call), it prints some 315228f6c2f2SEnji Cooperwarning messages, including the arguments of the function, the return value, and 315328f6c2f2SEnji Cooperthe stack trace. Hopefully this will remind you to take a look and see if there 315428f6c2f2SEnji Cooperis indeed a problem. 315528f6c2f2SEnji Cooper 315628f6c2f2SEnji CooperSometimes you are confident that your tests are correct and may not appreciate 315728f6c2f2SEnji Coopersuch friendly messages. Some other times, you are debugging your tests or 315828f6c2f2SEnji Cooperlearning about the behavior of the code you are testing, and wish you could 315928f6c2f2SEnji Cooperobserve every mock call that happens (including argument values, the return 316028f6c2f2SEnji Coopervalue, and the stack trace). Clearly, one size doesn't fit all. 316128f6c2f2SEnji Cooper 316228f6c2f2SEnji CooperYou can control how much gMock tells you using the `--gmock_verbose=LEVEL` 316328f6c2f2SEnji Coopercommand-line flag, where `LEVEL` is a string with three possible values: 316428f6c2f2SEnji Cooper 316528f6c2f2SEnji Cooper* `info`: gMock will print all informational messages, warnings, and errors 316628f6c2f2SEnji Cooper (most verbose). At this setting, gMock will also log any calls to the 316728f6c2f2SEnji Cooper `ON_CALL/EXPECT_CALL` macros. It will include a stack trace in 316828f6c2f2SEnji Cooper "uninteresting call" warnings. 316928f6c2f2SEnji Cooper* `warning`: gMock will print both warnings and errors (less verbose); it will 317028f6c2f2SEnji Cooper omit the stack traces in "uninteresting call" warnings. This is the default. 317128f6c2f2SEnji Cooper* `error`: gMock will print errors only (least verbose). 317228f6c2f2SEnji Cooper 317328f6c2f2SEnji CooperAlternatively, you can adjust the value of that flag from within your tests like 317428f6c2f2SEnji Cooperso: 317528f6c2f2SEnji Cooper 317628f6c2f2SEnji Cooper```cpp 317728f6c2f2SEnji Cooper ::testing::FLAGS_gmock_verbose = "error"; 317828f6c2f2SEnji Cooper``` 317928f6c2f2SEnji Cooper 318028f6c2f2SEnji CooperIf you find gMock printing too many stack frames with its informational or 318128f6c2f2SEnji Cooperwarning messages, remember that you can control their amount with the 318228f6c2f2SEnji Cooper`--gtest_stack_trace_depth=max_depth` flag. 318328f6c2f2SEnji Cooper 318428f6c2f2SEnji CooperNow, judiciously use the right flag to enable gMock serve you better! 318528f6c2f2SEnji Cooper 318628f6c2f2SEnji Cooper### Gaining Super Vision into Mock Calls 318728f6c2f2SEnji Cooper 318828f6c2f2SEnji CooperYou have a test using gMock. It fails: gMock tells you some expectations aren't 318928f6c2f2SEnji Coopersatisfied. However, you aren't sure why: Is there a typo somewhere in the 319028f6c2f2SEnji Coopermatchers? Did you mess up the order of the `EXPECT_CALL`s? Or is the code under 319128f6c2f2SEnji Coopertest doing something wrong? How can you find out the cause? 319228f6c2f2SEnji Cooper 319328f6c2f2SEnji CooperWon't it be nice if you have X-ray vision and can actually see the trace of all 319428f6c2f2SEnji Cooper`EXPECT_CALL`s and mock method calls as they are made? For each call, would you 319528f6c2f2SEnji Cooperlike to see its actual argument values and which `EXPECT_CALL` gMock thinks it 319628f6c2f2SEnji Coopermatches? If you still need some help to figure out who made these calls, how 319728f6c2f2SEnji Cooperabout being able to see the complete stack trace at each mock call? 319828f6c2f2SEnji Cooper 319928f6c2f2SEnji CooperYou can unlock this power by running your test with the `--gmock_verbose=info` 320028f6c2f2SEnji Cooperflag. For example, given the test program: 320128f6c2f2SEnji Cooper 320228f6c2f2SEnji Cooper```cpp 320328f6c2f2SEnji Cooper#include <gmock/gmock.h> 320428f6c2f2SEnji Cooper 320528f6c2f2SEnji Cooperusing ::testing::_; 320628f6c2f2SEnji Cooperusing ::testing::HasSubstr; 320728f6c2f2SEnji Cooperusing ::testing::Return; 320828f6c2f2SEnji Cooper 320928f6c2f2SEnji Cooperclass MockFoo { 321028f6c2f2SEnji Cooper public: 321128f6c2f2SEnji Cooper MOCK_METHOD(void, F, (const string& x, const string& y)); 321228f6c2f2SEnji Cooper}; 321328f6c2f2SEnji Cooper 321428f6c2f2SEnji CooperTEST(Foo, Bar) { 321528f6c2f2SEnji Cooper MockFoo mock; 321628f6c2f2SEnji Cooper EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return()); 321728f6c2f2SEnji Cooper EXPECT_CALL(mock, F("a", "b")); 321828f6c2f2SEnji Cooper EXPECT_CALL(mock, F("c", HasSubstr("d"))); 321928f6c2f2SEnji Cooper 322028f6c2f2SEnji Cooper mock.F("a", "good"); 322128f6c2f2SEnji Cooper mock.F("a", "b"); 322228f6c2f2SEnji Cooper} 322328f6c2f2SEnji Cooper``` 322428f6c2f2SEnji Cooper 322528f6c2f2SEnji Cooperif you run it with `--gmock_verbose=info`, you will see this output: 322628f6c2f2SEnji Cooper 322728f6c2f2SEnji Cooper```shell 322828f6c2f2SEnji Cooper[ RUN ] Foo.Bar 322928f6c2f2SEnji Cooper 323028f6c2f2SEnji Cooperfoo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked 323128f6c2f2SEnji CooperStack trace: ... 323228f6c2f2SEnji Cooper 323328f6c2f2SEnji Cooperfoo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked 323428f6c2f2SEnji CooperStack trace: ... 323528f6c2f2SEnji Cooper 323628f6c2f2SEnji Cooperfoo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked 323728f6c2f2SEnji CooperStack trace: ... 323828f6c2f2SEnji Cooper 323928f6c2f2SEnji Cooperfoo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))... 324028f6c2f2SEnji Cooper Function call: F(@0x7fff7c8dad40"a",@0x7fff7c8dad10"good") 324128f6c2f2SEnji CooperStack trace: ... 324228f6c2f2SEnji Cooper 324328f6c2f2SEnji Cooperfoo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))... 324428f6c2f2SEnji Cooper Function call: F(@0x7fff7c8dada0"a",@0x7fff7c8dad70"b") 324528f6c2f2SEnji CooperStack trace: ... 324628f6c2f2SEnji Cooper 324728f6c2f2SEnji Cooperfoo_test.cc:16: Failure 324828f6c2f2SEnji CooperActual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))... 324928f6c2f2SEnji Cooper Expected: to be called once 325028f6c2f2SEnji Cooper Actual: never called - unsatisfied and active 325128f6c2f2SEnji Cooper[ FAILED ] Foo.Bar 325228f6c2f2SEnji Cooper``` 325328f6c2f2SEnji Cooper 325428f6c2f2SEnji CooperSuppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo and 325528f6c2f2SEnji Coopershould actually be `"a"`. With the above message, you should see that the actual 325628f6c2f2SEnji Cooper`F("a", "good")` call is matched by the first `EXPECT_CALL`, not the third as 325728f6c2f2SEnji Cooperyou thought. From that it should be obvious that the third `EXPECT_CALL` is 325828f6c2f2SEnji Cooperwritten wrong. Case solved. 325928f6c2f2SEnji Cooper 326028f6c2f2SEnji CooperIf you are interested in the mock call trace but not the stack traces, you can 326128f6c2f2SEnji Coopercombine `--gmock_verbose=info` with `--gtest_stack_trace_depth=0` on the test 326228f6c2f2SEnji Coopercommand line. 326328f6c2f2SEnji Cooper 326428f6c2f2SEnji Cooper### Running Tests in Emacs 326528f6c2f2SEnji Cooper 326628f6c2f2SEnji CooperIf you build and run your tests in Emacs using the `M-x google-compile` command 326728f6c2f2SEnji Cooper(as many googletest users do), the source file locations of gMock and googletest 326828f6c2f2SEnji Coopererrors will be highlighted. Just press `<Enter>` on one of them and you'll be 326928f6c2f2SEnji Coopertaken to the offending line. Or, you can just type `C-x`` to jump to the next 327028f6c2f2SEnji Coopererror. 327128f6c2f2SEnji Cooper 327228f6c2f2SEnji CooperTo make it even easier, you can add the following lines to your `~/.emacs` file: 327328f6c2f2SEnji Cooper 327428f6c2f2SEnji Cooper```text 327528f6c2f2SEnji Cooper(global-set-key "\M-m" 'google-compile) ; m is for make 327628f6c2f2SEnji Cooper(global-set-key [M-down] 'next-error) 327728f6c2f2SEnji Cooper(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) 327828f6c2f2SEnji Cooper``` 327928f6c2f2SEnji Cooper 328028f6c2f2SEnji CooperThen you can type `M-m` to start a build (if you want to run the test as well, 328128f6c2f2SEnji Cooperjust make sure `foo_test.run` or `runtests` is in the build command you supply 328228f6c2f2SEnji Cooperafter typing `M-m`), or `M-up`/`M-down` to move back and forth between errors. 328328f6c2f2SEnji Cooper 328428f6c2f2SEnji Cooper## Extending gMock 328528f6c2f2SEnji Cooper 328628f6c2f2SEnji Cooper### Writing New Matchers Quickly {#NewMatchers} 328728f6c2f2SEnji Cooper 328828f6c2f2SEnji Cooper{: .callout .warning} 328928f6c2f2SEnji CooperWARNING: gMock does not guarantee when or how many times a matcher will be 329028f6c2f2SEnji Cooperinvoked. Therefore, all matchers must be functionally pure. See 329128f6c2f2SEnji Cooper[this section](#PureMatchers) for more details. 329228f6c2f2SEnji Cooper 329328f6c2f2SEnji CooperThe `MATCHER*` family of macros can be used to define custom matchers easily. 329428f6c2f2SEnji CooperThe syntax: 329528f6c2f2SEnji Cooper 329628f6c2f2SEnji Cooper```cpp 329728f6c2f2SEnji CooperMATCHER(name, description_string_expression) { statements; } 329828f6c2f2SEnji Cooper``` 329928f6c2f2SEnji Cooper 330028f6c2f2SEnji Cooperwill define a matcher with the given name that executes the statements, which 330128f6c2f2SEnji Coopermust return a `bool` to indicate if the match succeeds. Inside the statements, 330228f6c2f2SEnji Cooperyou can refer to the value being matched by `arg`, and refer to its type by 330328f6c2f2SEnji Cooper`arg_type`. 330428f6c2f2SEnji Cooper 330528f6c2f2SEnji CooperThe *description string* is a `string`-typed expression that documents what the 330628f6c2f2SEnji Coopermatcher does, and is used to generate the failure message when the match fails. 330728f6c2f2SEnji CooperIt can (and should) reference the special `bool` variable `negation`, and should 330828f6c2f2SEnji Cooperevaluate to the description of the matcher when `negation` is `false`, or that 330928f6c2f2SEnji Cooperof the matcher's negation when `negation` is `true`. 331028f6c2f2SEnji Cooper 331128f6c2f2SEnji CooperFor convenience, we allow the description string to be empty (`""`), in which 331228f6c2f2SEnji Coopercase gMock will use the sequence of words in the matcher name as the 331328f6c2f2SEnji Cooperdescription. 331428f6c2f2SEnji Cooper 3315*5ca8c28cSEnji Cooper#### Basic Example 331628f6c2f2SEnji Cooper 331728f6c2f2SEnji Cooper```cpp 331828f6c2f2SEnji CooperMATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } 331928f6c2f2SEnji Cooper``` 332028f6c2f2SEnji Cooper 332128f6c2f2SEnji Cooperallows you to write 332228f6c2f2SEnji Cooper 332328f6c2f2SEnji Cooper```cpp 332428f6c2f2SEnji Cooper // Expects mock_foo.Bar(n) to be called where n is divisible by 7. 332528f6c2f2SEnji Cooper EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); 332628f6c2f2SEnji Cooper``` 332728f6c2f2SEnji Cooper 332828f6c2f2SEnji Cooperor, 332928f6c2f2SEnji Cooper 333028f6c2f2SEnji Cooper```cpp 333128f6c2f2SEnji Cooper using ::testing::Not; 333228f6c2f2SEnji Cooper ... 333328f6c2f2SEnji Cooper // Verifies that a value is divisible by 7 and the other is not. 333428f6c2f2SEnji Cooper EXPECT_THAT(some_expression, IsDivisibleBy7()); 333528f6c2f2SEnji Cooper EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); 333628f6c2f2SEnji Cooper``` 333728f6c2f2SEnji Cooper 333828f6c2f2SEnji CooperIf the above assertions fail, they will print something like: 333928f6c2f2SEnji Cooper 334028f6c2f2SEnji Cooper```shell 334128f6c2f2SEnji Cooper Value of: some_expression 334228f6c2f2SEnji Cooper Expected: is divisible by 7 334328f6c2f2SEnji Cooper Actual: 27 334428f6c2f2SEnji Cooper ... 334528f6c2f2SEnji Cooper Value of: some_other_expression 334628f6c2f2SEnji Cooper Expected: not (is divisible by 7) 334728f6c2f2SEnji Cooper Actual: 21 334828f6c2f2SEnji Cooper``` 334928f6c2f2SEnji Cooper 335028f6c2f2SEnji Cooperwhere the descriptions `"is divisible by 7"` and `"not (is divisible by 7)"` are 335128f6c2f2SEnji Cooperautomatically calculated from the matcher name `IsDivisibleBy7`. 335228f6c2f2SEnji Cooper 3353*5ca8c28cSEnji Cooper#### Adding Custom Failure Messages 3354*5ca8c28cSEnji Cooper 335528f6c2f2SEnji CooperAs you may have noticed, the auto-generated descriptions (especially those for 335628f6c2f2SEnji Cooperthe negation) may not be so great. You can always override them with a `string` 335728f6c2f2SEnji Cooperexpression of your own: 335828f6c2f2SEnji Cooper 335928f6c2f2SEnji Cooper```cpp 336028f6c2f2SEnji CooperMATCHER(IsDivisibleBy7, 336128f6c2f2SEnji Cooper absl::StrCat(negation ? "isn't" : "is", " divisible by 7")) { 336228f6c2f2SEnji Cooper return (arg % 7) == 0; 336328f6c2f2SEnji Cooper} 336428f6c2f2SEnji Cooper``` 336528f6c2f2SEnji Cooper 336628f6c2f2SEnji CooperOptionally, you can stream additional information to a hidden argument named 336728f6c2f2SEnji Cooper`result_listener` to explain the match result. For example, a better definition 336828f6c2f2SEnji Cooperof `IsDivisibleBy7` is: 336928f6c2f2SEnji Cooper 337028f6c2f2SEnji Cooper```cpp 337128f6c2f2SEnji CooperMATCHER(IsDivisibleBy7, "") { 337228f6c2f2SEnji Cooper if ((arg % 7) == 0) 337328f6c2f2SEnji Cooper return true; 337428f6c2f2SEnji Cooper 337528f6c2f2SEnji Cooper *result_listener << "the remainder is " << (arg % 7); 337628f6c2f2SEnji Cooper return false; 337728f6c2f2SEnji Cooper} 337828f6c2f2SEnji Cooper``` 337928f6c2f2SEnji Cooper 338028f6c2f2SEnji CooperWith this definition, the above assertion will give a better message: 338128f6c2f2SEnji Cooper 338228f6c2f2SEnji Cooper```shell 338328f6c2f2SEnji Cooper Value of: some_expression 338428f6c2f2SEnji Cooper Expected: is divisible by 7 338528f6c2f2SEnji Cooper Actual: 27 (the remainder is 6) 338628f6c2f2SEnji Cooper``` 338728f6c2f2SEnji Cooper 3388*5ca8c28cSEnji Cooper#### Using EXPECT_ Statements in Matchers 3389*5ca8c28cSEnji Cooper 3390*5ca8c28cSEnji CooperYou can also use `EXPECT_...` (and `ASSERT_...`) statements inside custom 3391*5ca8c28cSEnji Coopermatcher definitions. In many cases, this allows you to write your matcher more 3392*5ca8c28cSEnji Cooperconcisely while still providing an informative error message. For example: 3393*5ca8c28cSEnji Cooper 3394*5ca8c28cSEnji Cooper```cpp 3395*5ca8c28cSEnji CooperMATCHER(IsDivisibleBy7, "") { 3396*5ca8c28cSEnji Cooper const auto remainder = arg % 7; 3397*5ca8c28cSEnji Cooper EXPECT_EQ(remainder, 0); 3398*5ca8c28cSEnji Cooper return true; 3399*5ca8c28cSEnji Cooper} 3400*5ca8c28cSEnji Cooper``` 3401*5ca8c28cSEnji Cooper 3402*5ca8c28cSEnji CooperIf you write a test that includes the line `EXPECT_THAT(27, IsDivisibleBy7());`, 3403*5ca8c28cSEnji Cooperyou will get an error something like the following: 3404*5ca8c28cSEnji Cooper 3405*5ca8c28cSEnji Cooper```shell 3406*5ca8c28cSEnji CooperExpected equality of these values: 3407*5ca8c28cSEnji Cooper remainder 3408*5ca8c28cSEnji Cooper Which is: 6 3409*5ca8c28cSEnji Cooper 0 3410*5ca8c28cSEnji Cooper``` 3411*5ca8c28cSEnji Cooper 3412*5ca8c28cSEnji Cooper#### `MatchAndExplain` 3413*5ca8c28cSEnji Cooper 341428f6c2f2SEnji CooperYou should let `MatchAndExplain()` print *any additional information* that can 341528f6c2f2SEnji Cooperhelp a user understand the match result. Note that it should explain why the 341628f6c2f2SEnji Coopermatch succeeds in case of a success (unless it's obvious) - this is useful when 341728f6c2f2SEnji Cooperthe matcher is used inside `Not()`. There is no need to print the argument value 341828f6c2f2SEnji Cooperitself, as gMock already prints it for you. 341928f6c2f2SEnji Cooper 3420*5ca8c28cSEnji Cooper#### Argument Types 3421*5ca8c28cSEnji Cooper 3422*5ca8c28cSEnji CooperThe type of the value being matched (`arg_type`) is determined by the 342328f6c2f2SEnji Coopercontext in which you use the matcher and is supplied to you by the compiler, so 342428f6c2f2SEnji Cooperyou don't need to worry about declaring it (nor can you). This allows the 342528f6c2f2SEnji Coopermatcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match 342628f6c2f2SEnji Cooperany type where the value of `(arg % 7) == 0` can be implicitly converted to a 342728f6c2f2SEnji Cooper`bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an 342828f6c2f2SEnji Cooper`int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will 342928f6c2f2SEnji Cooperbe `unsigned long`; and so on. 343028f6c2f2SEnji Cooper 343128f6c2f2SEnji Cooper### Writing New Parameterized Matchers Quickly 343228f6c2f2SEnji Cooper 343328f6c2f2SEnji CooperSometimes you'll want to define a matcher that has parameters. For that you can 343428f6c2f2SEnji Cooperuse the macro: 343528f6c2f2SEnji Cooper 343628f6c2f2SEnji Cooper```cpp 343728f6c2f2SEnji CooperMATCHER_P(name, param_name, description_string) { statements; } 343828f6c2f2SEnji Cooper``` 343928f6c2f2SEnji Cooper 344028f6c2f2SEnji Cooperwhere the description string can be either `""` or a `string` expression that 344128f6c2f2SEnji Cooperreferences `negation` and `param_name`. 344228f6c2f2SEnji Cooper 344328f6c2f2SEnji CooperFor example: 344428f6c2f2SEnji Cooper 344528f6c2f2SEnji Cooper```cpp 344628f6c2f2SEnji CooperMATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } 344728f6c2f2SEnji Cooper``` 344828f6c2f2SEnji Cooper 344928f6c2f2SEnji Cooperwill allow you to write: 345028f6c2f2SEnji Cooper 345128f6c2f2SEnji Cooper```cpp 345228f6c2f2SEnji Cooper EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); 345328f6c2f2SEnji Cooper``` 345428f6c2f2SEnji Cooper 345528f6c2f2SEnji Cooperwhich may lead to this message (assuming `n` is 10): 345628f6c2f2SEnji Cooper 345728f6c2f2SEnji Cooper```shell 345828f6c2f2SEnji Cooper Value of: Blah("a") 345928f6c2f2SEnji Cooper Expected: has absolute value 10 346028f6c2f2SEnji Cooper Actual: -9 346128f6c2f2SEnji Cooper``` 346228f6c2f2SEnji Cooper 346328f6c2f2SEnji CooperNote that both the matcher description and its parameter are printed, making the 346428f6c2f2SEnji Coopermessage human-friendly. 346528f6c2f2SEnji Cooper 346628f6c2f2SEnji CooperIn the matcher definition body, you can write `foo_type` to reference the type 346728f6c2f2SEnji Cooperof a parameter named `foo`. For example, in the body of 346828f6c2f2SEnji Cooper`MATCHER_P(HasAbsoluteValue, value)` above, you can write `value_type` to refer 346928f6c2f2SEnji Cooperto the type of `value`. 347028f6c2f2SEnji Cooper 347128f6c2f2SEnji CoopergMock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to `MATCHER_P10` to 347228f6c2f2SEnji Coopersupport multi-parameter matchers: 347328f6c2f2SEnji Cooper 347428f6c2f2SEnji Cooper```cpp 347528f6c2f2SEnji CooperMATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } 347628f6c2f2SEnji Cooper``` 347728f6c2f2SEnji Cooper 347828f6c2f2SEnji CooperPlease note that the custom description string is for a particular *instance* of 347928f6c2f2SEnji Cooperthe matcher, where the parameters have been bound to actual values. Therefore 348028f6c2f2SEnji Cooperusually you'll want the parameter values to be part of the description. gMock 348128f6c2f2SEnji Cooperlets you do that by referencing the matcher parameters in the description string 348228f6c2f2SEnji Cooperexpression. 348328f6c2f2SEnji Cooper 348428f6c2f2SEnji CooperFor example, 348528f6c2f2SEnji Cooper 348628f6c2f2SEnji Cooper```cpp 348728f6c2f2SEnji Cooperusing ::testing::PrintToString; 348828f6c2f2SEnji CooperMATCHER_P2(InClosedRange, low, hi, 348928f6c2f2SEnji Cooper absl::StrFormat("%s in range [%s, %s]", negation ? "isn't" : "is", 349028f6c2f2SEnji Cooper PrintToString(low), PrintToString(hi))) { 349128f6c2f2SEnji Cooper return low <= arg && arg <= hi; 349228f6c2f2SEnji Cooper} 349328f6c2f2SEnji Cooper... 349428f6c2f2SEnji CooperEXPECT_THAT(3, InClosedRange(4, 6)); 349528f6c2f2SEnji Cooper``` 349628f6c2f2SEnji Cooper 349728f6c2f2SEnji Cooperwould generate a failure that contains the message: 349828f6c2f2SEnji Cooper 349928f6c2f2SEnji Cooper```shell 350028f6c2f2SEnji Cooper Expected: is in range [4, 6] 350128f6c2f2SEnji Cooper``` 350228f6c2f2SEnji Cooper 350328f6c2f2SEnji CooperIf you specify `""` as the description, the failure message will contain the 350428f6c2f2SEnji Coopersequence of words in the matcher name followed by the parameter values printed 350528f6c2f2SEnji Cooperas a tuple. For example, 350628f6c2f2SEnji Cooper 350728f6c2f2SEnji Cooper```cpp 350828f6c2f2SEnji Cooper MATCHER_P2(InClosedRange, low, hi, "") { ... } 350928f6c2f2SEnji Cooper ... 351028f6c2f2SEnji Cooper EXPECT_THAT(3, InClosedRange(4, 6)); 351128f6c2f2SEnji Cooper``` 351228f6c2f2SEnji Cooper 351328f6c2f2SEnji Cooperwould generate a failure that contains the text: 351428f6c2f2SEnji Cooper 351528f6c2f2SEnji Cooper```shell 351628f6c2f2SEnji Cooper Expected: in closed range (4, 6) 351728f6c2f2SEnji Cooper``` 351828f6c2f2SEnji Cooper 351928f6c2f2SEnji CooperFor the purpose of typing, you can view 352028f6c2f2SEnji Cooper 352128f6c2f2SEnji Cooper```cpp 352228f6c2f2SEnji CooperMATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } 352328f6c2f2SEnji Cooper``` 352428f6c2f2SEnji Cooper 352528f6c2f2SEnji Cooperas shorthand for 352628f6c2f2SEnji Cooper 352728f6c2f2SEnji Cooper```cpp 352828f6c2f2SEnji Coopertemplate <typename p1_type, ..., typename pk_type> 352928f6c2f2SEnji CooperFooMatcherPk<p1_type, ..., pk_type> 353028f6c2f2SEnji CooperFoo(p1_type p1, ..., pk_type pk) { ... } 353128f6c2f2SEnji Cooper``` 353228f6c2f2SEnji Cooper 353328f6c2f2SEnji CooperWhen you write `Foo(v1, ..., vk)`, the compiler infers the types of the 353428f6c2f2SEnji Cooperparameters `v1`, ..., and `vk` for you. If you are not happy with the result of 353528f6c2f2SEnji Cooperthe type inference, you can specify the types by explicitly instantiating the 353628f6c2f2SEnji Coopertemplate, as in `Foo<long, bool>(5, false)`. As said earlier, you don't get to 353728f6c2f2SEnji Cooper(or need to) specify `arg_type` as that's determined by the context in which the 353828f6c2f2SEnji Coopermatcher is used. 353928f6c2f2SEnji Cooper 354028f6c2f2SEnji CooperYou can assign the result of expression `Foo(p1, ..., pk)` to a variable of type 354128f6c2f2SEnji Cooper`FooMatcherPk<p1_type, ..., pk_type>`. This can be useful when composing 354228f6c2f2SEnji Coopermatchers. Matchers that don't have a parameter or have only one parameter have 354328f6c2f2SEnji Cooperspecial types: you can assign `Foo()` to a `FooMatcher`-typed variable, and 354428f6c2f2SEnji Cooperassign `Foo(p)` to a `FooMatcherP<p_type>`-typed variable. 354528f6c2f2SEnji Cooper 354628f6c2f2SEnji CooperWhile you can instantiate a matcher template with reference types, passing the 354728f6c2f2SEnji Cooperparameters by pointer usually makes your code more readable. If, however, you 354828f6c2f2SEnji Cooperstill want to pass a parameter by reference, be aware that in the failure 354928f6c2f2SEnji Coopermessage generated by the matcher you will see the value of the referenced object 355028f6c2f2SEnji Cooperbut not its address. 355128f6c2f2SEnji Cooper 355228f6c2f2SEnji CooperYou can overload matchers with different numbers of parameters: 355328f6c2f2SEnji Cooper 355428f6c2f2SEnji Cooper```cpp 355528f6c2f2SEnji CooperMATCHER_P(Blah, a, description_string_1) { ... } 355628f6c2f2SEnji CooperMATCHER_P2(Blah, a, b, description_string_2) { ... } 355728f6c2f2SEnji Cooper``` 355828f6c2f2SEnji Cooper 355928f6c2f2SEnji CooperWhile it's tempting to always use the `MATCHER*` macros when defining a new 356028f6c2f2SEnji Coopermatcher, you should also consider implementing the matcher interface directly 356128f6c2f2SEnji Cooperinstead (see the recipes that follow), especially if you need to use the matcher 356228f6c2f2SEnji Coopera lot. While these approaches require more work, they give you more control on 356328f6c2f2SEnji Cooperthe types of the value being matched and the matcher parameters, which in 356428f6c2f2SEnji Coopergeneral leads to better compiler error messages that pay off in the long run. 356528f6c2f2SEnji CooperThey also allow overloading matchers based on parameter types (as opposed to 356628f6c2f2SEnji Cooperjust based on the number of parameters). 356728f6c2f2SEnji Cooper 356828f6c2f2SEnji Cooper### Writing New Monomorphic Matchers 356928f6c2f2SEnji Cooper 357028f6c2f2SEnji CooperA matcher of argument type `T` implements the matcher interface for `T` and does 357128f6c2f2SEnji Coopertwo things: it tests whether a value of type `T` matches the matcher, and can 357228f6c2f2SEnji Cooperdescribe what kind of values it matches. The latter ability is used for 357328f6c2f2SEnji Coopergenerating readable error messages when expectations are violated. 357428f6c2f2SEnji Cooper 357528f6c2f2SEnji CooperA matcher of `T` must declare a typedef like: 357628f6c2f2SEnji Cooper 357728f6c2f2SEnji Cooper```cpp 357828f6c2f2SEnji Cooperusing is_gtest_matcher = void; 357928f6c2f2SEnji Cooper``` 358028f6c2f2SEnji Cooper 358128f6c2f2SEnji Cooperand supports the following operations: 358228f6c2f2SEnji Cooper 358328f6c2f2SEnji Cooper```cpp 358428f6c2f2SEnji Cooper// Match a value and optionally explain into an ostream. 358528f6c2f2SEnji Cooperbool matched = matcher.MatchAndExplain(value, maybe_os); 358628f6c2f2SEnji Cooper// where `value` is of type `T` and 358728f6c2f2SEnji Cooper// `maybe_os` is of type `std::ostream*`, where it can be null if the caller 358828f6c2f2SEnji Cooper// is not interested in there textual explanation. 358928f6c2f2SEnji Cooper 359028f6c2f2SEnji Coopermatcher.DescribeTo(os); 359128f6c2f2SEnji Coopermatcher.DescribeNegationTo(os); 359228f6c2f2SEnji Cooper// where `os` is of type `std::ostream*`. 359328f6c2f2SEnji Cooper``` 359428f6c2f2SEnji Cooper 359528f6c2f2SEnji CooperIf you need a custom matcher but `Truly()` is not a good option (for example, 359628f6c2f2SEnji Cooperyou may not be happy with the way `Truly(predicate)` describes itself, or you 359728f6c2f2SEnji Coopermay want your matcher to be polymorphic as `Eq(value)` is), you can define a 359828f6c2f2SEnji Coopermatcher to do whatever you want in two steps: first implement the matcher 359928f6c2f2SEnji Cooperinterface, and then define a factory function to create a matcher instance. The 360028f6c2f2SEnji Coopersecond step is not strictly needed but it makes the syntax of using the matcher 360128f6c2f2SEnji Coopernicer. 360228f6c2f2SEnji Cooper 360328f6c2f2SEnji CooperFor example, you can define a matcher to test whether an `int` is divisible by 7 360428f6c2f2SEnji Cooperand then use it like this: 360528f6c2f2SEnji Cooper 360628f6c2f2SEnji Cooper```cpp 360728f6c2f2SEnji Cooperusing ::testing::Matcher; 360828f6c2f2SEnji Cooper 360928f6c2f2SEnji Cooperclass DivisibleBy7Matcher { 361028f6c2f2SEnji Cooper public: 361128f6c2f2SEnji Cooper using is_gtest_matcher = void; 361228f6c2f2SEnji Cooper 361328f6c2f2SEnji Cooper bool MatchAndExplain(int n, std::ostream*) const { 361428f6c2f2SEnji Cooper return (n % 7) == 0; 361528f6c2f2SEnji Cooper } 361628f6c2f2SEnji Cooper 361728f6c2f2SEnji Cooper void DescribeTo(std::ostream* os) const { 361828f6c2f2SEnji Cooper *os << "is divisible by 7"; 361928f6c2f2SEnji Cooper } 362028f6c2f2SEnji Cooper 362128f6c2f2SEnji Cooper void DescribeNegationTo(std::ostream* os) const { 362228f6c2f2SEnji Cooper *os << "is not divisible by 7"; 362328f6c2f2SEnji Cooper } 362428f6c2f2SEnji Cooper}; 362528f6c2f2SEnji Cooper 362628f6c2f2SEnji CooperMatcher<int> DivisibleBy7() { 362728f6c2f2SEnji Cooper return DivisibleBy7Matcher(); 362828f6c2f2SEnji Cooper} 362928f6c2f2SEnji Cooper 363028f6c2f2SEnji Cooper... 363128f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar(DivisibleBy7())); 363228f6c2f2SEnji Cooper``` 363328f6c2f2SEnji Cooper 363428f6c2f2SEnji CooperYou may improve the matcher message by streaming additional information to the 363528f6c2f2SEnji Cooper`os` argument in `MatchAndExplain()`: 363628f6c2f2SEnji Cooper 363728f6c2f2SEnji Cooper```cpp 363828f6c2f2SEnji Cooperclass DivisibleBy7Matcher { 363928f6c2f2SEnji Cooper public: 364028f6c2f2SEnji Cooper bool MatchAndExplain(int n, std::ostream* os) const { 364128f6c2f2SEnji Cooper const int remainder = n % 7; 364228f6c2f2SEnji Cooper if (remainder != 0 && os != nullptr) { 364328f6c2f2SEnji Cooper *os << "the remainder is " << remainder; 364428f6c2f2SEnji Cooper } 364528f6c2f2SEnji Cooper return remainder == 0; 364628f6c2f2SEnji Cooper } 364728f6c2f2SEnji Cooper ... 364828f6c2f2SEnji Cooper}; 364928f6c2f2SEnji Cooper``` 365028f6c2f2SEnji Cooper 365128f6c2f2SEnji CooperThen, `EXPECT_THAT(x, DivisibleBy7());` may generate a message like this: 365228f6c2f2SEnji Cooper 365328f6c2f2SEnji Cooper```shell 365428f6c2f2SEnji CooperValue of: x 365528f6c2f2SEnji CooperExpected: is divisible by 7 365628f6c2f2SEnji Cooper Actual: 23 (the remainder is 2) 365728f6c2f2SEnji Cooper``` 365828f6c2f2SEnji Cooper 365928f6c2f2SEnji Cooper{: .callout .tip} 366028f6c2f2SEnji CooperTip: for convenience, `MatchAndExplain()` can take a `MatchResultListener*` 366128f6c2f2SEnji Cooperinstead of `std::ostream*`. 366228f6c2f2SEnji Cooper 366328f6c2f2SEnji Cooper### Writing New Polymorphic Matchers 366428f6c2f2SEnji Cooper 366528f6c2f2SEnji CooperExpanding what we learned above to *polymorphic* matchers is now just as simple 366628f6c2f2SEnji Cooperas adding templates in the right place. 366728f6c2f2SEnji Cooper 366828f6c2f2SEnji Cooper```cpp 366928f6c2f2SEnji Cooper 367028f6c2f2SEnji Cooperclass NotNullMatcher { 367128f6c2f2SEnji Cooper public: 367228f6c2f2SEnji Cooper using is_gtest_matcher = void; 367328f6c2f2SEnji Cooper 367428f6c2f2SEnji Cooper // To implement a polymorphic matcher, we just need to make MatchAndExplain a 367528f6c2f2SEnji Cooper // template on its first argument. 367628f6c2f2SEnji Cooper 367728f6c2f2SEnji Cooper // In this example, we want to use NotNull() with any pointer, so 367828f6c2f2SEnji Cooper // MatchAndExplain() accepts a pointer of any type as its first argument. 367928f6c2f2SEnji Cooper // In general, you can define MatchAndExplain() as an ordinary method or 368028f6c2f2SEnji Cooper // a method template, or even overload it. 368128f6c2f2SEnji Cooper template <typename T> 368228f6c2f2SEnji Cooper bool MatchAndExplain(T* p, std::ostream*) const { 368328f6c2f2SEnji Cooper return p != nullptr; 368428f6c2f2SEnji Cooper } 368528f6c2f2SEnji Cooper 368628f6c2f2SEnji Cooper // Describes the property of a value matching this matcher. 368728f6c2f2SEnji Cooper void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } 368828f6c2f2SEnji Cooper 368928f6c2f2SEnji Cooper // Describes the property of a value NOT matching this matcher. 369028f6c2f2SEnji Cooper void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } 369128f6c2f2SEnji Cooper}; 369228f6c2f2SEnji Cooper 369328f6c2f2SEnji CooperNotNullMatcher NotNull() { 369428f6c2f2SEnji Cooper return NotNullMatcher(); 369528f6c2f2SEnji Cooper} 369628f6c2f2SEnji Cooper 369728f6c2f2SEnji Cooper... 369828f6c2f2SEnji Cooper 369928f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. 370028f6c2f2SEnji Cooper``` 370128f6c2f2SEnji Cooper 370228f6c2f2SEnji Cooper### Legacy Matcher Implementation 370328f6c2f2SEnji Cooper 370428f6c2f2SEnji CooperDefining matchers used to be somewhat more complicated, in which it required 370528f6c2f2SEnji Cooperseveral supporting classes and virtual functions. To implement a matcher for 370628f6c2f2SEnji Coopertype `T` using the legacy API you have to derive from `MatcherInterface<T>` and 370728f6c2f2SEnji Coopercall `MakeMatcher` to construct the object. 370828f6c2f2SEnji Cooper 370928f6c2f2SEnji CooperThe interface looks like this: 371028f6c2f2SEnji Cooper 371128f6c2f2SEnji Cooper```cpp 371228f6c2f2SEnji Cooperclass MatchResultListener { 371328f6c2f2SEnji Cooper public: 371428f6c2f2SEnji Cooper ... 371528f6c2f2SEnji Cooper // Streams x to the underlying ostream; does nothing if the ostream 371628f6c2f2SEnji Cooper // is NULL. 371728f6c2f2SEnji Cooper template <typename T> 371828f6c2f2SEnji Cooper MatchResultListener& operator<<(const T& x); 371928f6c2f2SEnji Cooper 372028f6c2f2SEnji Cooper // Returns the underlying ostream. 372128f6c2f2SEnji Cooper std::ostream* stream(); 372228f6c2f2SEnji Cooper}; 372328f6c2f2SEnji Cooper 372428f6c2f2SEnji Coopertemplate <typename T> 372528f6c2f2SEnji Cooperclass MatcherInterface { 372628f6c2f2SEnji Cooper public: 372728f6c2f2SEnji Cooper virtual ~MatcherInterface(); 372828f6c2f2SEnji Cooper 372928f6c2f2SEnji Cooper // Returns true if and only if the matcher matches x; also explains the match 373028f6c2f2SEnji Cooper // result to 'listener'. 373128f6c2f2SEnji Cooper virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; 373228f6c2f2SEnji Cooper 373328f6c2f2SEnji Cooper // Describes this matcher to an ostream. 373428f6c2f2SEnji Cooper virtual void DescribeTo(std::ostream* os) const = 0; 373528f6c2f2SEnji Cooper 373628f6c2f2SEnji Cooper // Describes the negation of this matcher to an ostream. 373728f6c2f2SEnji Cooper virtual void DescribeNegationTo(std::ostream* os) const; 373828f6c2f2SEnji Cooper}; 373928f6c2f2SEnji Cooper``` 374028f6c2f2SEnji Cooper 374128f6c2f2SEnji CooperFortunately, most of the time you can define a polymorphic matcher easily with 374228f6c2f2SEnji Cooperthe help of `MakePolymorphicMatcher()`. Here's how you can define `NotNull()` as 374328f6c2f2SEnji Cooperan example: 374428f6c2f2SEnji Cooper 374528f6c2f2SEnji Cooper```cpp 374628f6c2f2SEnji Cooperusing ::testing::MakePolymorphicMatcher; 374728f6c2f2SEnji Cooperusing ::testing::MatchResultListener; 374828f6c2f2SEnji Cooperusing ::testing::PolymorphicMatcher; 374928f6c2f2SEnji Cooper 375028f6c2f2SEnji Cooperclass NotNullMatcher { 375128f6c2f2SEnji Cooper public: 375228f6c2f2SEnji Cooper // To implement a polymorphic matcher, first define a COPYABLE class 375328f6c2f2SEnji Cooper // that has three members MatchAndExplain(), DescribeTo(), and 375428f6c2f2SEnji Cooper // DescribeNegationTo(), like the following. 375528f6c2f2SEnji Cooper 375628f6c2f2SEnji Cooper // In this example, we want to use NotNull() with any pointer, so 375728f6c2f2SEnji Cooper // MatchAndExplain() accepts a pointer of any type as its first argument. 375828f6c2f2SEnji Cooper // In general, you can define MatchAndExplain() as an ordinary method or 375928f6c2f2SEnji Cooper // a method template, or even overload it. 376028f6c2f2SEnji Cooper template <typename T> 376128f6c2f2SEnji Cooper bool MatchAndExplain(T* p, 376228f6c2f2SEnji Cooper MatchResultListener* /* listener */) const { 376328f6c2f2SEnji Cooper return p != NULL; 376428f6c2f2SEnji Cooper } 376528f6c2f2SEnji Cooper 376628f6c2f2SEnji Cooper // Describes the property of a value matching this matcher. 376728f6c2f2SEnji Cooper void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } 376828f6c2f2SEnji Cooper 376928f6c2f2SEnji Cooper // Describes the property of a value NOT matching this matcher. 377028f6c2f2SEnji Cooper void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } 377128f6c2f2SEnji Cooper}; 377228f6c2f2SEnji Cooper 377328f6c2f2SEnji Cooper// To construct a polymorphic matcher, pass an instance of the class 377428f6c2f2SEnji Cooper// to MakePolymorphicMatcher(). Note the return type. 377528f6c2f2SEnji CooperPolymorphicMatcher<NotNullMatcher> NotNull() { 377628f6c2f2SEnji Cooper return MakePolymorphicMatcher(NotNullMatcher()); 377728f6c2f2SEnji Cooper} 377828f6c2f2SEnji Cooper 377928f6c2f2SEnji Cooper... 378028f6c2f2SEnji Cooper 378128f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. 378228f6c2f2SEnji Cooper``` 378328f6c2f2SEnji Cooper 378428f6c2f2SEnji Cooper{: .callout .note} 378528f6c2f2SEnji Cooper**Note:** Your polymorphic matcher class does **not** need to inherit from 378628f6c2f2SEnji Cooper`MatcherInterface` or any other class, and its methods do **not** need to be 378728f6c2f2SEnji Coopervirtual. 378828f6c2f2SEnji Cooper 378928f6c2f2SEnji CooperLike in a monomorphic matcher, you may explain the match result by streaming 379028f6c2f2SEnji Cooperadditional information to the `listener` argument in `MatchAndExplain()`. 379128f6c2f2SEnji Cooper 379228f6c2f2SEnji Cooper### Writing New Cardinalities 379328f6c2f2SEnji Cooper 379428f6c2f2SEnji CooperA cardinality is used in `Times()` to tell gMock how many times you expect a 379528f6c2f2SEnji Coopercall to occur. It doesn't have to be exact. For example, you can say 379628f6c2f2SEnji Cooper`AtLeast(5)` or `Between(2, 4)`. 379728f6c2f2SEnji Cooper 379828f6c2f2SEnji CooperIf the [built-in set](gmock_cheat_sheet.md#CardinalityList) of cardinalities 379928f6c2f2SEnji Cooperdoesn't suit you, you are free to define your own by implementing the following 380028f6c2f2SEnji Cooperinterface (in namespace `testing`): 380128f6c2f2SEnji Cooper 380228f6c2f2SEnji Cooper```cpp 380328f6c2f2SEnji Cooperclass CardinalityInterface { 380428f6c2f2SEnji Cooper public: 380528f6c2f2SEnji Cooper virtual ~CardinalityInterface(); 380628f6c2f2SEnji Cooper 380728f6c2f2SEnji Cooper // Returns true if and only if call_count calls will satisfy this cardinality. 380828f6c2f2SEnji Cooper virtual bool IsSatisfiedByCallCount(int call_count) const = 0; 380928f6c2f2SEnji Cooper 381028f6c2f2SEnji Cooper // Returns true if and only if call_count calls will saturate this 381128f6c2f2SEnji Cooper // cardinality. 381228f6c2f2SEnji Cooper virtual bool IsSaturatedByCallCount(int call_count) const = 0; 381328f6c2f2SEnji Cooper 381428f6c2f2SEnji Cooper // Describes self to an ostream. 381528f6c2f2SEnji Cooper virtual void DescribeTo(std::ostream* os) const = 0; 381628f6c2f2SEnji Cooper}; 381728f6c2f2SEnji Cooper``` 381828f6c2f2SEnji Cooper 381928f6c2f2SEnji CooperFor example, to specify that a call must occur even number of times, you can 382028f6c2f2SEnji Cooperwrite 382128f6c2f2SEnji Cooper 382228f6c2f2SEnji Cooper```cpp 382328f6c2f2SEnji Cooperusing ::testing::Cardinality; 382428f6c2f2SEnji Cooperusing ::testing::CardinalityInterface; 382528f6c2f2SEnji Cooperusing ::testing::MakeCardinality; 382628f6c2f2SEnji Cooper 382728f6c2f2SEnji Cooperclass EvenNumberCardinality : public CardinalityInterface { 382828f6c2f2SEnji Cooper public: 382928f6c2f2SEnji Cooper bool IsSatisfiedByCallCount(int call_count) const override { 383028f6c2f2SEnji Cooper return (call_count % 2) == 0; 383128f6c2f2SEnji Cooper } 383228f6c2f2SEnji Cooper 383328f6c2f2SEnji Cooper bool IsSaturatedByCallCount(int call_count) const override { 383428f6c2f2SEnji Cooper return false; 383528f6c2f2SEnji Cooper } 383628f6c2f2SEnji Cooper 383728f6c2f2SEnji Cooper void DescribeTo(std::ostream* os) const { 383828f6c2f2SEnji Cooper *os << "called even number of times"; 383928f6c2f2SEnji Cooper } 384028f6c2f2SEnji Cooper}; 384128f6c2f2SEnji Cooper 384228f6c2f2SEnji CooperCardinality EvenNumber() { 384328f6c2f2SEnji Cooper return MakeCardinality(new EvenNumberCardinality); 384428f6c2f2SEnji Cooper} 384528f6c2f2SEnji Cooper 384628f6c2f2SEnji Cooper... 384728f6c2f2SEnji Cooper EXPECT_CALL(foo, Bar(3)) 384828f6c2f2SEnji Cooper .Times(EvenNumber()); 384928f6c2f2SEnji Cooper``` 385028f6c2f2SEnji Cooper 385128f6c2f2SEnji Cooper### Writing New Actions {#QuickNewActions} 385228f6c2f2SEnji Cooper 385328f6c2f2SEnji CooperIf the built-in actions don't work for you, you can easily define your own one. 385428f6c2f2SEnji CooperAll you need is a call operator with a signature compatible with the mocked 385528f6c2f2SEnji Cooperfunction. So you can use a lambda: 385628f6c2f2SEnji Cooper 385728f6c2f2SEnji Cooper```cpp 385828f6c2f2SEnji CooperMockFunction<int(int)> mock; 385928f6c2f2SEnji CooperEXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; }); 386028f6c2f2SEnji CooperEXPECT_EQ(mock.AsStdFunction()(2), 14); 386128f6c2f2SEnji Cooper``` 386228f6c2f2SEnji Cooper 386328f6c2f2SEnji CooperOr a struct with a call operator (even a templated one): 386428f6c2f2SEnji Cooper 386528f6c2f2SEnji Cooper```cpp 386628f6c2f2SEnji Cooperstruct MultiplyBy { 386728f6c2f2SEnji Cooper template <typename T> 386828f6c2f2SEnji Cooper T operator()(T arg) { return arg * multiplier; } 386928f6c2f2SEnji Cooper 387028f6c2f2SEnji Cooper int multiplier; 387128f6c2f2SEnji Cooper}; 387228f6c2f2SEnji Cooper 387328f6c2f2SEnji Cooper// Then use: 387428f6c2f2SEnji Cooper// EXPECT_CALL(...).WillOnce(MultiplyBy{7}); 387528f6c2f2SEnji Cooper``` 387628f6c2f2SEnji Cooper 387728f6c2f2SEnji CooperIt's also fine for the callable to take no arguments, ignoring the arguments 387828f6c2f2SEnji Coopersupplied to the mock function: 387928f6c2f2SEnji Cooper 388028f6c2f2SEnji Cooper```cpp 388128f6c2f2SEnji CooperMockFunction<int(int)> mock; 388228f6c2f2SEnji CooperEXPECT_CALL(mock, Call).WillOnce([] { return 17; }); 388328f6c2f2SEnji CooperEXPECT_EQ(mock.AsStdFunction()(0), 17); 388428f6c2f2SEnji Cooper``` 388528f6c2f2SEnji Cooper 388628f6c2f2SEnji CooperWhen used with `WillOnce`, the callable can assume it will be called at most 388728f6c2f2SEnji Cooperonce and is allowed to be a move-only type: 388828f6c2f2SEnji Cooper 388928f6c2f2SEnji Cooper```cpp 389028f6c2f2SEnji Cooper// An action that contains move-only types and has an &&-qualified operator, 389128f6c2f2SEnji Cooper// demanding in the type system that it be called at most once. This can be 389228f6c2f2SEnji Cooper// used with WillOnce, but the compiler will reject it if handed to 389328f6c2f2SEnji Cooper// WillRepeatedly. 389428f6c2f2SEnji Cooperstruct MoveOnlyAction { 389528f6c2f2SEnji Cooper std::unique_ptr<int> move_only_state; 389628f6c2f2SEnji Cooper std::unique_ptr<int> operator()() && { return std::move(move_only_state); } 389728f6c2f2SEnji Cooper}; 389828f6c2f2SEnji Cooper 389928f6c2f2SEnji CooperMockFunction<std::unique_ptr<int>()> mock; 390028f6c2f2SEnji CooperEXPECT_CALL(mock, Call).WillOnce(MoveOnlyAction{std::make_unique<int>(17)}); 390128f6c2f2SEnji CooperEXPECT_THAT(mock.AsStdFunction()(), Pointee(Eq(17))); 390228f6c2f2SEnji Cooper``` 390328f6c2f2SEnji Cooper 390428f6c2f2SEnji CooperMore generally, to use with a mock function whose signature is `R(Args...)` the 390528f6c2f2SEnji Cooperobject can be anything convertible to `OnceAction<R(Args...)>` or 390628f6c2f2SEnji Cooper`Action<R(Args...)`>. The difference between the two is that `OnceAction` has 390728f6c2f2SEnji Cooperweaker requirements (`Action` requires a copy-constructible input that can be 390828f6c2f2SEnji Coopercalled repeatedly whereas `OnceAction` requires only move-constructible and 390928f6c2f2SEnji Coopersupports `&&`-qualified call operators), but can be used only with `WillOnce`. 391028f6c2f2SEnji Cooper`OnceAction` is typically relevant only when supporting move-only types or 391128f6c2f2SEnji Cooperactions that want a type-system guarantee that they will be called at most once. 391228f6c2f2SEnji Cooper 391328f6c2f2SEnji CooperTypically the `OnceAction` and `Action` templates need not be referenced 391428f6c2f2SEnji Cooperdirectly in your actions: a struct or class with a call operator is sufficient, 391528f6c2f2SEnji Cooperas in the examples above. But fancier polymorphic actions that need to know the 391628f6c2f2SEnji Cooperspecific return type of the mock function can define templated conversion 391728f6c2f2SEnji Cooperoperators to make that possible. See `gmock-actions.h` for examples. 391828f6c2f2SEnji Cooper 391928f6c2f2SEnji Cooper#### Legacy macro-based Actions 392028f6c2f2SEnji Cooper 392128f6c2f2SEnji CooperBefore C++11, the functor-based actions were not supported; the old way of 392228f6c2f2SEnji Cooperwriting actions was through a set of `ACTION*` macros. We suggest to avoid them 392328f6c2f2SEnji Cooperin new code; they hide a lot of logic behind the macro, potentially leading to 392428f6c2f2SEnji Cooperharder-to-understand compiler errors. Nevertheless, we cover them here for 392528f6c2f2SEnji Coopercompleteness. 392628f6c2f2SEnji Cooper 392728f6c2f2SEnji CooperBy writing 392828f6c2f2SEnji Cooper 392928f6c2f2SEnji Cooper```cpp 393028f6c2f2SEnji CooperACTION(name) { statements; } 393128f6c2f2SEnji Cooper``` 393228f6c2f2SEnji Cooper 393328f6c2f2SEnji Cooperin a namespace scope (i.e. not inside a class or function), you will define an 393428f6c2f2SEnji Cooperaction with the given name that executes the statements. The value returned by 393528f6c2f2SEnji Cooper`statements` will be used as the return value of the action. Inside the 393628f6c2f2SEnji Cooperstatements, you can refer to the K-th (0-based) argument of the mock function as 393728f6c2f2SEnji Cooper`argK`. For example: 393828f6c2f2SEnji Cooper 393928f6c2f2SEnji Cooper```cpp 394028f6c2f2SEnji CooperACTION(IncrementArg1) { return ++(*arg1); } 394128f6c2f2SEnji Cooper``` 394228f6c2f2SEnji Cooper 394328f6c2f2SEnji Cooperallows you to write 394428f6c2f2SEnji Cooper 394528f6c2f2SEnji Cooper```cpp 394628f6c2f2SEnji Cooper... WillOnce(IncrementArg1()); 394728f6c2f2SEnji Cooper``` 394828f6c2f2SEnji Cooper 394928f6c2f2SEnji CooperNote that you don't need to specify the types of the mock function arguments. 395028f6c2f2SEnji CooperRest assured that your code is type-safe though: you'll get a compiler error if 395128f6c2f2SEnji Cooper`*arg1` doesn't support the `++` operator, or if the type of `++(*arg1)` isn't 395228f6c2f2SEnji Coopercompatible with the mock function's return type. 395328f6c2f2SEnji Cooper 395428f6c2f2SEnji CooperAnother example: 395528f6c2f2SEnji Cooper 395628f6c2f2SEnji Cooper```cpp 395728f6c2f2SEnji CooperACTION(Foo) { 395828f6c2f2SEnji Cooper (*arg2)(5); 395928f6c2f2SEnji Cooper Blah(); 396028f6c2f2SEnji Cooper *arg1 = 0; 396128f6c2f2SEnji Cooper return arg0; 396228f6c2f2SEnji Cooper} 396328f6c2f2SEnji Cooper``` 396428f6c2f2SEnji Cooper 396528f6c2f2SEnji Cooperdefines an action `Foo()` that invokes argument #2 (a function pointer) with 5, 396628f6c2f2SEnji Coopercalls function `Blah()`, sets the value pointed to by argument #1 to 0, and 396728f6c2f2SEnji Cooperreturns argument #0. 396828f6c2f2SEnji Cooper 396928f6c2f2SEnji CooperFor more convenience and flexibility, you can also use the following pre-defined 397028f6c2f2SEnji Coopersymbols in the body of `ACTION`: 397128f6c2f2SEnji Cooper 397228f6c2f2SEnji Cooper`argK_type` | The type of the K-th (0-based) argument of the mock function 397328f6c2f2SEnji Cooper:-------------- | :----------------------------------------------------------- 397428f6c2f2SEnji Cooper`args` | All arguments of the mock function as a tuple 397528f6c2f2SEnji Cooper`args_type` | The type of all arguments of the mock function as a tuple 397628f6c2f2SEnji Cooper`return_type` | The return type of the mock function 397728f6c2f2SEnji Cooper`function_type` | The type of the mock function 397828f6c2f2SEnji Cooper 397928f6c2f2SEnji CooperFor example, when using an `ACTION` as a stub action for mock function: 398028f6c2f2SEnji Cooper 398128f6c2f2SEnji Cooper```cpp 398228f6c2f2SEnji Cooperint DoSomething(bool flag, int* ptr); 398328f6c2f2SEnji Cooper``` 398428f6c2f2SEnji Cooper 398528f6c2f2SEnji Cooperwe have: 398628f6c2f2SEnji Cooper 398728f6c2f2SEnji CooperPre-defined Symbol | Is Bound To 398828f6c2f2SEnji Cooper------------------ | --------------------------------- 398928f6c2f2SEnji Cooper`arg0` | the value of `flag` 399028f6c2f2SEnji Cooper`arg0_type` | the type `bool` 399128f6c2f2SEnji Cooper`arg1` | the value of `ptr` 399228f6c2f2SEnji Cooper`arg1_type` | the type `int*` 399328f6c2f2SEnji Cooper`args` | the tuple `(flag, ptr)` 399428f6c2f2SEnji Cooper`args_type` | the type `std::tuple<bool, int*>` 399528f6c2f2SEnji Cooper`return_type` | the type `int` 399628f6c2f2SEnji Cooper`function_type` | the type `int(bool, int*)` 399728f6c2f2SEnji Cooper 399828f6c2f2SEnji Cooper#### Legacy macro-based parameterized Actions 399928f6c2f2SEnji Cooper 400028f6c2f2SEnji CooperSometimes you'll want to parameterize an action you define. For that we have 400128f6c2f2SEnji Cooperanother macro 400228f6c2f2SEnji Cooper 400328f6c2f2SEnji Cooper```cpp 400428f6c2f2SEnji CooperACTION_P(name, param) { statements; } 400528f6c2f2SEnji Cooper``` 400628f6c2f2SEnji Cooper 400728f6c2f2SEnji CooperFor example, 400828f6c2f2SEnji Cooper 400928f6c2f2SEnji Cooper```cpp 401028f6c2f2SEnji CooperACTION_P(Add, n) { return arg0 + n; } 401128f6c2f2SEnji Cooper``` 401228f6c2f2SEnji Cooper 401328f6c2f2SEnji Cooperwill allow you to write 401428f6c2f2SEnji Cooper 401528f6c2f2SEnji Cooper```cpp 401628f6c2f2SEnji Cooper// Returns argument #0 + 5. 401728f6c2f2SEnji Cooper... WillOnce(Add(5)); 401828f6c2f2SEnji Cooper``` 401928f6c2f2SEnji Cooper 402028f6c2f2SEnji CooperFor convenience, we use the term *arguments* for the values used to invoke the 402128f6c2f2SEnji Coopermock function, and the term *parameters* for the values used to instantiate an 402228f6c2f2SEnji Cooperaction. 402328f6c2f2SEnji Cooper 402428f6c2f2SEnji CooperNote that you don't need to provide the type of the parameter either. Suppose 402528f6c2f2SEnji Cooperthe parameter is named `param`, you can also use the gMock-defined symbol 402628f6c2f2SEnji Cooper`param_type` to refer to the type of the parameter as inferred by the compiler. 402728f6c2f2SEnji CooperFor example, in the body of `ACTION_P(Add, n)` above, you can write `n_type` for 402828f6c2f2SEnji Cooperthe type of `n`. 402928f6c2f2SEnji Cooper 403028f6c2f2SEnji CoopergMock also provides `ACTION_P2`, `ACTION_P3`, and etc to support multi-parameter 403128f6c2f2SEnji Cooperactions. For example, 403228f6c2f2SEnji Cooper 403328f6c2f2SEnji Cooper```cpp 403428f6c2f2SEnji CooperACTION_P2(ReturnDistanceTo, x, y) { 403528f6c2f2SEnji Cooper double dx = arg0 - x; 403628f6c2f2SEnji Cooper double dy = arg1 - y; 403728f6c2f2SEnji Cooper return sqrt(dx*dx + dy*dy); 403828f6c2f2SEnji Cooper} 403928f6c2f2SEnji Cooper``` 404028f6c2f2SEnji Cooper 404128f6c2f2SEnji Cooperlets you write 404228f6c2f2SEnji Cooper 404328f6c2f2SEnji Cooper```cpp 404428f6c2f2SEnji Cooper... WillOnce(ReturnDistanceTo(5.0, 26.5)); 404528f6c2f2SEnji Cooper``` 404628f6c2f2SEnji Cooper 404728f6c2f2SEnji CooperYou can view `ACTION` as a degenerated parameterized action where the number of 404828f6c2f2SEnji Cooperparameters is 0. 404928f6c2f2SEnji Cooper 405028f6c2f2SEnji CooperYou can also easily define actions overloaded on the number of parameters: 405128f6c2f2SEnji Cooper 405228f6c2f2SEnji Cooper```cpp 405328f6c2f2SEnji CooperACTION_P(Plus, a) { ... } 405428f6c2f2SEnji CooperACTION_P2(Plus, a, b) { ... } 405528f6c2f2SEnji Cooper``` 405628f6c2f2SEnji Cooper 405728f6c2f2SEnji Cooper### Restricting the Type of an Argument or Parameter in an ACTION 405828f6c2f2SEnji Cooper 405928f6c2f2SEnji CooperFor maximum brevity and reusability, the `ACTION*` macros don't ask you to 406028f6c2f2SEnji Cooperprovide the types of the mock function arguments and the action parameters. 406128f6c2f2SEnji CooperInstead, we let the compiler infer the types for us. 406228f6c2f2SEnji Cooper 406328f6c2f2SEnji CooperSometimes, however, we may want to be more explicit about the types. There are 406428f6c2f2SEnji Cooperseveral tricks to do that. For example: 406528f6c2f2SEnji Cooper 406628f6c2f2SEnji Cooper```cpp 406728f6c2f2SEnji CooperACTION(Foo) { 406828f6c2f2SEnji Cooper // Makes sure arg0 can be converted to int. 406928f6c2f2SEnji Cooper int n = arg0; 407028f6c2f2SEnji Cooper ... use n instead of arg0 here ... 407128f6c2f2SEnji Cooper} 407228f6c2f2SEnji Cooper 407328f6c2f2SEnji CooperACTION_P(Bar, param) { 407428f6c2f2SEnji Cooper // Makes sure the type of arg1 is const char*. 407528f6c2f2SEnji Cooper ::testing::StaticAssertTypeEq<const char*, arg1_type>(); 407628f6c2f2SEnji Cooper 407728f6c2f2SEnji Cooper // Makes sure param can be converted to bool. 407828f6c2f2SEnji Cooper bool flag = param; 407928f6c2f2SEnji Cooper} 408028f6c2f2SEnji Cooper``` 408128f6c2f2SEnji Cooper 408228f6c2f2SEnji Cooperwhere `StaticAssertTypeEq` is a compile-time assertion in googletest that 408328f6c2f2SEnji Cooperverifies two types are the same. 408428f6c2f2SEnji Cooper 408528f6c2f2SEnji Cooper### Writing New Action Templates Quickly 408628f6c2f2SEnji Cooper 408728f6c2f2SEnji CooperSometimes you want to give an action explicit template parameters that cannot be 408828f6c2f2SEnji Cooperinferred from its value parameters. `ACTION_TEMPLATE()` supports that and can be 408928f6c2f2SEnji Cooperviewed as an extension to `ACTION()` and `ACTION_P*()`. 409028f6c2f2SEnji Cooper 409128f6c2f2SEnji CooperThe syntax: 409228f6c2f2SEnji Cooper 409328f6c2f2SEnji Cooper```cpp 409428f6c2f2SEnji CooperACTION_TEMPLATE(ActionName, 409528f6c2f2SEnji Cooper HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), 409628f6c2f2SEnji Cooper AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } 409728f6c2f2SEnji Cooper``` 409828f6c2f2SEnji Cooper 409928f6c2f2SEnji Cooperdefines an action template that takes *m* explicit template parameters and *n* 410028f6c2f2SEnji Coopervalue parameters, where *m* is in [1, 10] and *n* is in [0, 10]. `name_i` is the 410128f6c2f2SEnji Coopername of the *i*-th template parameter, and `kind_i` specifies whether it's a 410228f6c2f2SEnji Cooper`typename`, an integral constant, or a template. `p_i` is the name of the *i*-th 410328f6c2f2SEnji Coopervalue parameter. 410428f6c2f2SEnji Cooper 410528f6c2f2SEnji CooperExample: 410628f6c2f2SEnji Cooper 410728f6c2f2SEnji Cooper```cpp 410828f6c2f2SEnji Cooper// DuplicateArg<k, T>(output) converts the k-th argument of the mock 410928f6c2f2SEnji Cooper// function to type T and copies it to *output. 411028f6c2f2SEnji CooperACTION_TEMPLATE(DuplicateArg, 411128f6c2f2SEnji Cooper // Note the comma between int and k: 411228f6c2f2SEnji Cooper HAS_2_TEMPLATE_PARAMS(int, k, typename, T), 411328f6c2f2SEnji Cooper AND_1_VALUE_PARAMS(output)) { 411428f6c2f2SEnji Cooper *output = T(std::get<k>(args)); 411528f6c2f2SEnji Cooper} 411628f6c2f2SEnji Cooper``` 411728f6c2f2SEnji Cooper 411828f6c2f2SEnji CooperTo create an instance of an action template, write: 411928f6c2f2SEnji Cooper 412028f6c2f2SEnji Cooper```cpp 412128f6c2f2SEnji CooperActionName<t1, ..., t_m>(v1, ..., v_n) 412228f6c2f2SEnji Cooper``` 412328f6c2f2SEnji Cooper 412428f6c2f2SEnji Cooperwhere the `t`s are the template arguments and the `v`s are the value arguments. 412528f6c2f2SEnji CooperThe value argument types are inferred by the compiler. For example: 412628f6c2f2SEnji Cooper 412728f6c2f2SEnji Cooper```cpp 412828f6c2f2SEnji Cooperusing ::testing::_; 412928f6c2f2SEnji Cooper... 413028f6c2f2SEnji Cooper int n; 413128f6c2f2SEnji Cooper EXPECT_CALL(mock, Foo).WillOnce(DuplicateArg<1, unsigned char>(&n)); 413228f6c2f2SEnji Cooper``` 413328f6c2f2SEnji Cooper 413428f6c2f2SEnji CooperIf you want to explicitly specify the value argument types, you can provide 413528f6c2f2SEnji Cooperadditional template arguments: 413628f6c2f2SEnji Cooper 413728f6c2f2SEnji Cooper```cpp 413828f6c2f2SEnji CooperActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n) 413928f6c2f2SEnji Cooper``` 414028f6c2f2SEnji Cooper 414128f6c2f2SEnji Cooperwhere `u_i` is the desired type of `v_i`. 414228f6c2f2SEnji Cooper 414328f6c2f2SEnji Cooper`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the number of 414428f6c2f2SEnji Coopervalue parameters, but not on the number of template parameters. Without the 414528f6c2f2SEnji Cooperrestriction, the meaning of the following is unclear: 414628f6c2f2SEnji Cooper 414728f6c2f2SEnji Cooper```cpp 414828f6c2f2SEnji Cooper OverloadedAction<int, bool>(x); 414928f6c2f2SEnji Cooper``` 415028f6c2f2SEnji Cooper 415128f6c2f2SEnji CooperAre we using a single-template-parameter action where `bool` refers to the type 415228f6c2f2SEnji Cooperof `x`, or a two-template-parameter action where the compiler is asked to infer 415328f6c2f2SEnji Cooperthe type of `x`? 415428f6c2f2SEnji Cooper 415528f6c2f2SEnji Cooper### Using the ACTION Object's Type 415628f6c2f2SEnji Cooper 415728f6c2f2SEnji CooperIf you are writing a function that returns an `ACTION` object, you'll need to 415828f6c2f2SEnji Cooperknow its type. The type depends on the macro used to define the action and the 415928f6c2f2SEnji Cooperparameter types. The rule is relatively simple: 416028f6c2f2SEnji Cooper 416128f6c2f2SEnji Cooper 416228f6c2f2SEnji Cooper| Given Definition | Expression | Has Type | 416328f6c2f2SEnji Cooper| ----------------------------- | ------------------- | --------------------- | 416428f6c2f2SEnji Cooper| `ACTION(Foo)` | `Foo()` | `FooAction` | 416528f6c2f2SEnji Cooper| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` | 416628f6c2f2SEnji Cooper| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` | 416728f6c2f2SEnji Cooper| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `BarActionP<t1, ..., t_m, int>` | 416828f6c2f2SEnji Cooper| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` | 416928f6c2f2SEnji Cooper| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `BazActionP2<t1, ..., t_m, bool, int>` | 417028f6c2f2SEnji Cooper| ... | ... | ... | 417128f6c2f2SEnji Cooper 417228f6c2f2SEnji Cooper 417328f6c2f2SEnji CooperNote that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`, 417428f6c2f2SEnji Cooperand etc) for actions with different numbers of value parameters, or the action 417528f6c2f2SEnji Cooperdefinitions cannot be overloaded on the number of them. 417628f6c2f2SEnji Cooper 417728f6c2f2SEnji Cooper### Writing New Monomorphic Actions {#NewMonoActions} 417828f6c2f2SEnji Cooper 417928f6c2f2SEnji CooperWhile the `ACTION*` macros are very convenient, sometimes they are 418028f6c2f2SEnji Cooperinappropriate. For example, despite the tricks shown in the previous recipes, 418128f6c2f2SEnji Cooperthey don't let you directly specify the types of the mock function arguments and 418228f6c2f2SEnji Cooperthe action parameters, which in general leads to unoptimized compiler error 418328f6c2f2SEnji Coopermessages that can baffle unfamiliar users. They also don't allow overloading 418428f6c2f2SEnji Cooperactions based on parameter types without jumping through some hoops. 418528f6c2f2SEnji Cooper 418628f6c2f2SEnji CooperAn alternative to the `ACTION*` macros is to implement 418728f6c2f2SEnji Cooper`::testing::ActionInterface<F>`, where `F` is the type of the mock function in 418828f6c2f2SEnji Cooperwhich the action will be used. For example: 418928f6c2f2SEnji Cooper 419028f6c2f2SEnji Cooper```cpp 419128f6c2f2SEnji Coopertemplate <typename F> 419228f6c2f2SEnji Cooperclass ActionInterface { 419328f6c2f2SEnji Cooper public: 419428f6c2f2SEnji Cooper virtual ~ActionInterface(); 419528f6c2f2SEnji Cooper 419628f6c2f2SEnji Cooper // Performs the action. Result is the return type of function type 419728f6c2f2SEnji Cooper // F, and ArgumentTuple is the tuple of arguments of F. 419828f6c2f2SEnji Cooper // 419928f6c2f2SEnji Cooper 420028f6c2f2SEnji Cooper // For example, if F is int(bool, const string&), then Result would 420128f6c2f2SEnji Cooper // be int, and ArgumentTuple would be std::tuple<bool, const string&>. 420228f6c2f2SEnji Cooper virtual Result Perform(const ArgumentTuple& args) = 0; 420328f6c2f2SEnji Cooper}; 420428f6c2f2SEnji Cooper``` 420528f6c2f2SEnji Cooper 420628f6c2f2SEnji Cooper```cpp 420728f6c2f2SEnji Cooperusing ::testing::_; 420828f6c2f2SEnji Cooperusing ::testing::Action; 420928f6c2f2SEnji Cooperusing ::testing::ActionInterface; 421028f6c2f2SEnji Cooperusing ::testing::MakeAction; 421128f6c2f2SEnji Cooper 421228f6c2f2SEnji Coopertypedef int IncrementMethod(int*); 421328f6c2f2SEnji Cooper 421428f6c2f2SEnji Cooperclass IncrementArgumentAction : public ActionInterface<IncrementMethod> { 421528f6c2f2SEnji Cooper public: 421628f6c2f2SEnji Cooper int Perform(const std::tuple<int*>& args) override { 421728f6c2f2SEnji Cooper int* p = std::get<0>(args); // Grabs the first argument. 421828f6c2f2SEnji Cooper return *p++; 421928f6c2f2SEnji Cooper } 422028f6c2f2SEnji Cooper}; 422128f6c2f2SEnji Cooper 422228f6c2f2SEnji CooperAction<IncrementMethod> IncrementArgument() { 422328f6c2f2SEnji Cooper return MakeAction(new IncrementArgumentAction); 422428f6c2f2SEnji Cooper} 422528f6c2f2SEnji Cooper 422628f6c2f2SEnji Cooper... 422728f6c2f2SEnji Cooper EXPECT_CALL(foo, Baz(_)) 422828f6c2f2SEnji Cooper .WillOnce(IncrementArgument()); 422928f6c2f2SEnji Cooper 423028f6c2f2SEnji Cooper int n = 5; 423128f6c2f2SEnji Cooper foo.Baz(&n); // Should return 5 and change n to 6. 423228f6c2f2SEnji Cooper``` 423328f6c2f2SEnji Cooper 423428f6c2f2SEnji Cooper### Writing New Polymorphic Actions {#NewPolyActions} 423528f6c2f2SEnji Cooper 423628f6c2f2SEnji CooperThe previous recipe showed you how to define your own action. This is all good, 423728f6c2f2SEnji Cooperexcept that you need to know the type of the function in which the action will 423828f6c2f2SEnji Cooperbe used. Sometimes that can be a problem. For example, if you want to use the 423928f6c2f2SEnji Cooperaction in functions with *different* types (e.g. like `Return()` and 424028f6c2f2SEnji Cooper`SetArgPointee()`). 424128f6c2f2SEnji Cooper 424228f6c2f2SEnji CooperIf an action can be used in several types of mock functions, we say it's 424328f6c2f2SEnji Cooper*polymorphic*. The `MakePolymorphicAction()` function template makes it easy to 424428f6c2f2SEnji Cooperdefine such an action: 424528f6c2f2SEnji Cooper 424628f6c2f2SEnji Cooper```cpp 424728f6c2f2SEnji Coopernamespace testing { 424828f6c2f2SEnji Coopertemplate <typename Impl> 424928f6c2f2SEnji CooperPolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl); 425028f6c2f2SEnji Cooper} // namespace testing 425128f6c2f2SEnji Cooper``` 425228f6c2f2SEnji Cooper 425328f6c2f2SEnji CooperAs an example, let's define an action that returns the second argument in the 425428f6c2f2SEnji Coopermock function's argument list. The first step is to define an implementation 425528f6c2f2SEnji Cooperclass: 425628f6c2f2SEnji Cooper 425728f6c2f2SEnji Cooper```cpp 425828f6c2f2SEnji Cooperclass ReturnSecondArgumentAction { 425928f6c2f2SEnji Cooper public: 426028f6c2f2SEnji Cooper template <typename Result, typename ArgumentTuple> 426128f6c2f2SEnji Cooper Result Perform(const ArgumentTuple& args) const { 426228f6c2f2SEnji Cooper // To get the i-th (0-based) argument, use std::get(args). 426328f6c2f2SEnji Cooper return std::get<1>(args); 426428f6c2f2SEnji Cooper } 426528f6c2f2SEnji Cooper}; 426628f6c2f2SEnji Cooper``` 426728f6c2f2SEnji Cooper 426828f6c2f2SEnji CooperThis implementation class does *not* need to inherit from any particular class. 426928f6c2f2SEnji CooperWhat matters is that it must have a `Perform()` method template. This method 427028f6c2f2SEnji Coopertemplate takes the mock function's arguments as a tuple in a **single** 427128f6c2f2SEnji Cooperargument, and returns the result of the action. It can be either `const` or not, 427228f6c2f2SEnji Cooperbut must be invocable with exactly one template argument, which is the result 427328f6c2f2SEnji Coopertype. In other words, you must be able to call `Perform<R>(args)` where `R` is 427428f6c2f2SEnji Cooperthe mock function's return type and `args` is its arguments in a tuple. 427528f6c2f2SEnji Cooper 427628f6c2f2SEnji CooperNext, we use `MakePolymorphicAction()` to turn an instance of the implementation 427728f6c2f2SEnji Cooperclass into the polymorphic action we need. It will be convenient to have a 427828f6c2f2SEnji Cooperwrapper for this: 427928f6c2f2SEnji Cooper 428028f6c2f2SEnji Cooper```cpp 428128f6c2f2SEnji Cooperusing ::testing::MakePolymorphicAction; 428228f6c2f2SEnji Cooperusing ::testing::PolymorphicAction; 428328f6c2f2SEnji Cooper 428428f6c2f2SEnji CooperPolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { 428528f6c2f2SEnji Cooper return MakePolymorphicAction(ReturnSecondArgumentAction()); 428628f6c2f2SEnji Cooper} 428728f6c2f2SEnji Cooper``` 428828f6c2f2SEnji Cooper 428928f6c2f2SEnji CooperNow, you can use this polymorphic action the same way you use the built-in ones: 429028f6c2f2SEnji Cooper 429128f6c2f2SEnji Cooper```cpp 429228f6c2f2SEnji Cooperusing ::testing::_; 429328f6c2f2SEnji Cooper 429428f6c2f2SEnji Cooperclass MockFoo : public Foo { 429528f6c2f2SEnji Cooper public: 429628f6c2f2SEnji Cooper MOCK_METHOD(int, DoThis, (bool flag, int n), (override)); 429728f6c2f2SEnji Cooper MOCK_METHOD(string, DoThat, (int x, const char* str1, const char* str2), 429828f6c2f2SEnji Cooper (override)); 429928f6c2f2SEnji Cooper}; 430028f6c2f2SEnji Cooper 430128f6c2f2SEnji Cooper ... 430228f6c2f2SEnji Cooper MockFoo foo; 430328f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThis).WillOnce(ReturnSecondArgument()); 430428f6c2f2SEnji Cooper EXPECT_CALL(foo, DoThat).WillOnce(ReturnSecondArgument()); 430528f6c2f2SEnji Cooper ... 430628f6c2f2SEnji Cooper foo.DoThis(true, 5); // Will return 5. 430728f6c2f2SEnji Cooper foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". 430828f6c2f2SEnji Cooper``` 430928f6c2f2SEnji Cooper 431028f6c2f2SEnji Cooper### Teaching gMock How to Print Your Values 431128f6c2f2SEnji Cooper 431228f6c2f2SEnji CooperWhen an uninteresting or unexpected call occurs, gMock prints the argument 431328f6c2f2SEnji Coopervalues and the stack trace to help you debug. Assertion macros like 431428f6c2f2SEnji Cooper`EXPECT_THAT` and `EXPECT_EQ` also print the values in question when the 431528f6c2f2SEnji Cooperassertion fails. gMock and googletest do this using googletest's user-extensible 431628f6c2f2SEnji Coopervalue printer. 431728f6c2f2SEnji Cooper 431828f6c2f2SEnji CooperThis printer knows how to print built-in C++ types, native arrays, STL 431928f6c2f2SEnji Coopercontainers, and any type that supports the `<<` operator. For other types, it 432028f6c2f2SEnji Cooperprints the raw bytes in the value and hopes that you the user can figure it out. 432128f6c2f2SEnji Cooper[The GoogleTest advanced guide](advanced.md#teaching-googletest-how-to-print-your-values) 432228f6c2f2SEnji Cooperexplains how to extend the printer to do a better job at printing your 432328f6c2f2SEnji Cooperparticular type than to dump the bytes. 432428f6c2f2SEnji Cooper 432528f6c2f2SEnji Cooper## Useful Mocks Created Using gMock 432628f6c2f2SEnji Cooper 432728f6c2f2SEnji Cooper<!--#include file="includes/g3_testing_LOGs.md"--> 432828f6c2f2SEnji Cooper<!--#include file="includes/g3_mock_callbacks.md"--> 432928f6c2f2SEnji Cooper 433028f6c2f2SEnji Cooper### Mock std::function {#MockFunction} 433128f6c2f2SEnji Cooper 433228f6c2f2SEnji Cooper`std::function` is a general function type introduced in C++11. It is a 433328f6c2f2SEnji Cooperpreferred way of passing callbacks to new interfaces. Functions are copyable, 433428f6c2f2SEnji Cooperand are not usually passed around by pointer, which makes them tricky to mock. 433528f6c2f2SEnji CooperBut fear not - `MockFunction` can help you with that. 433628f6c2f2SEnji Cooper 433728f6c2f2SEnji Cooper`MockFunction<R(T1, ..., Tn)>` has a mock method `Call()` with the signature: 433828f6c2f2SEnji Cooper 433928f6c2f2SEnji Cooper```cpp 434028f6c2f2SEnji Cooper R Call(T1, ..., Tn); 434128f6c2f2SEnji Cooper``` 434228f6c2f2SEnji Cooper 434328f6c2f2SEnji CooperIt also has a `AsStdFunction()` method, which creates a `std::function` proxy 434428f6c2f2SEnji Cooperforwarding to Call: 434528f6c2f2SEnji Cooper 434628f6c2f2SEnji Cooper```cpp 434728f6c2f2SEnji Cooper std::function<R(T1, ..., Tn)> AsStdFunction(); 434828f6c2f2SEnji Cooper``` 434928f6c2f2SEnji Cooper 435028f6c2f2SEnji CooperTo use `MockFunction`, first create `MockFunction` object and set up 435128f6c2f2SEnji Cooperexpectations on its `Call` method. Then pass proxy obtained from 435228f6c2f2SEnji Cooper`AsStdFunction()` to the code you are testing. For example: 435328f6c2f2SEnji Cooper 435428f6c2f2SEnji Cooper```cpp 435528f6c2f2SEnji CooperTEST(FooTest, RunsCallbackWithBarArgument) { 435628f6c2f2SEnji Cooper // 1. Create a mock object. 435728f6c2f2SEnji Cooper MockFunction<int(string)> mock_function; 435828f6c2f2SEnji Cooper 435928f6c2f2SEnji Cooper // 2. Set expectations on Call() method. 436028f6c2f2SEnji Cooper EXPECT_CALL(mock_function, Call("bar")).WillOnce(Return(1)); 436128f6c2f2SEnji Cooper 436228f6c2f2SEnji Cooper // 3. Exercise code that uses std::function. 436328f6c2f2SEnji Cooper Foo(mock_function.AsStdFunction()); 436428f6c2f2SEnji Cooper // Foo's signature can be either of: 436528f6c2f2SEnji Cooper // void Foo(const std::function<int(string)>& fun); 436628f6c2f2SEnji Cooper // void Foo(std::function<int(string)> fun); 436728f6c2f2SEnji Cooper 436828f6c2f2SEnji Cooper // 4. All expectations will be verified when mock_function 436928f6c2f2SEnji Cooper // goes out of scope and is destroyed. 437028f6c2f2SEnji Cooper} 437128f6c2f2SEnji Cooper``` 437228f6c2f2SEnji Cooper 437328f6c2f2SEnji CooperRemember that function objects created with `AsStdFunction()` are just 437428f6c2f2SEnji Cooperforwarders. If you create multiple of them, they will share the same set of 437528f6c2f2SEnji Cooperexpectations. 437628f6c2f2SEnji Cooper 437728f6c2f2SEnji CooperAlthough `std::function` supports unlimited number of arguments, `MockFunction` 437828f6c2f2SEnji Cooperimplementation is limited to ten. If you ever hit that limit... well, your 437928f6c2f2SEnji Coopercallback has bigger problems than being mockable. :-) 4380