You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

241 lines
7.2 KiB

3 months ago
  1. # gMock Cheat Sheet
  2. ## Defining a Mock Class
  3. ### Mocking a Normal Class {#MockClass}
  4. Given
  5. ```cpp
  6. class Foo {
  7. ...
  8. virtual ~Foo();
  9. virtual int GetSize() const = 0;
  10. virtual string Describe(const char* name) = 0;
  11. virtual string Describe(int type) = 0;
  12. virtual bool Process(Bar elem, int count) = 0;
  13. };
  14. ```
  15. (note that `~Foo()` **must** be virtual) we can define its mock as
  16. ```cpp
  17. #include "gmock/gmock.h"
  18. class MockFoo : public Foo {
  19. ...
  20. MOCK_METHOD(int, GetSize, (), (const, override));
  21. MOCK_METHOD(string, Describe, (const char* name), (override));
  22. MOCK_METHOD(string, Describe, (int type), (override));
  23. MOCK_METHOD(bool, Process, (Bar elem, int count), (override));
  24. };
  25. ```
  26. To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock,
  27. which warns on all uninteresting calls, or a "strict" mock, which treats them as
  28. failures:
  29. ```cpp
  30. using ::testing::NiceMock;
  31. using ::testing::NaggyMock;
  32. using ::testing::StrictMock;
  33. NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo.
  34. NaggyMock<MockFoo> naggy_foo; // The type is a subclass of MockFoo.
  35. StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
  36. ```
  37. {: .callout .note}
  38. **Note:** A mock object is currently naggy by default. We may make it nice by
  39. default in the future.
  40. ### Mocking a Class Template {#MockTemplate}
  41. Class templates can be mocked just like any class.
  42. To mock
  43. ```cpp
  44. template <typename Elem>
  45. class StackInterface {
  46. ...
  47. virtual ~StackInterface();
  48. virtual int GetSize() const = 0;
  49. virtual void Push(const Elem& x) = 0;
  50. };
  51. ```
  52. (note that all member functions that are mocked, including `~StackInterface()`
  53. **must** be virtual).
  54. ```cpp
  55. template <typename Elem>
  56. class MockStack : public StackInterface<Elem> {
  57. ...
  58. MOCK_METHOD(int, GetSize, (), (const, override));
  59. MOCK_METHOD(void, Push, (const Elem& x), (override));
  60. };
  61. ```
  62. ### Specifying Calling Conventions for Mock Functions
  63. If your mock function doesn't use the default calling convention, you can
  64. specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter.
  65. For example,
  66. ```cpp
  67. MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE)));
  68. MOCK_METHOD(int, Bar, (double x, double y),
  69. (const, Calltype(STDMETHODCALLTYPE)));
  70. ```
  71. where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
  72. ## Using Mocks in Tests {#UsingMocks}
  73. The typical work flow is:
  74. 1. Import the gMock names you need to use. All gMock symbols are in the
  75. `testing` namespace unless they are macros or otherwise noted.
  76. 2. Create the mock objects.
  77. 3. Optionally, set the default actions of the mock objects.
  78. 4. Set your expectations on the mock objects (How will they be called? What
  79. will they do?).
  80. 5. Exercise code that uses the mock objects; if necessary, check the result
  81. using googletest assertions.
  82. 6. When a mock object is destructed, gMock automatically verifies that all
  83. expectations on it have been satisfied.
  84. Here's an example:
  85. ```cpp
  86. using ::testing::Return; // #1
  87. TEST(BarTest, DoesThis) {
  88. MockFoo foo; // #2
  89. ON_CALL(foo, GetSize()) // #3
  90. .WillByDefault(Return(1));
  91. // ... other default actions ...
  92. EXPECT_CALL(foo, Describe(5)) // #4
  93. .Times(3)
  94. .WillRepeatedly(Return("Category 5"));
  95. // ... other expectations ...
  96. EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5
  97. } // #6
  98. ```
  99. ## Setting Default Actions {#OnCall}
  100. gMock has a **built-in default action** for any function that returns `void`,
  101. `bool`, a numeric value, or a pointer. In C++11, it will additionally returns
  102. the default-constructed value, if one exists for the given type.
  103. To customize the default action for functions with return type `T`, use
  104. [`DefaultValue<T>`](reference/mocking.md#DefaultValue). For example:
  105. ```cpp
  106. // Sets the default action for return type std::unique_ptr<Buzz> to
  107. // creating a new Buzz every time.
  108. DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
  109. [] { return MakeUnique<Buzz>(AccessLevel::kInternal); });
  110. // When this fires, the default action of MakeBuzz() will run, which
  111. // will return a new Buzz object.
  112. EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
  113. auto buzz1 = mock_buzzer_.MakeBuzz("hello");
  114. auto buzz2 = mock_buzzer_.MakeBuzz("hello");
  115. EXPECT_NE(buzz1, nullptr);
  116. EXPECT_NE(buzz2, nullptr);
  117. EXPECT_NE(buzz1, buzz2);
  118. // Resets the default action for return type std::unique_ptr<Buzz>,
  119. // to avoid interfere with other tests.
  120. DefaultValue<std::unique_ptr<Buzz>>::Clear();
  121. ```
  122. To customize the default action for a particular method of a specific mock
  123. object, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar
  124. syntax to `EXPECT_CALL`, but it is used for setting default behaviors when you
  125. do not require that the mock method is called. See
  126. [Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed
  127. discussion.
  128. ## Setting Expectations {#ExpectCall}
  129. See [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference.
  130. ## Matchers {#MatcherList}
  131. See the [Matchers Reference](reference/matchers.md).
  132. ## Actions {#ActionList}
  133. See the [Actions Reference](reference/actions.md).
  134. ## Cardinalities {#CardinalityList}
  135. See the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of
  136. `EXPECT_CALL` in the Mocking Reference.
  137. ## Expectation Order
  138. By default, expectations can be matched in *any* order. If some or all
  139. expectations must be matched in a given order, you can use the
  140. [`After` clause](reference/mocking.md#EXPECT_CALL.After) or
  141. [`InSequence` clause](reference/mocking.md#EXPECT_CALL.InSequence) of
  142. `EXPECT_CALL`, or use an [`InSequence` object](reference/mocking.md#InSequence).
  143. ## Verifying and Resetting a Mock
  144. gMock will verify the expectations on a mock object when it is destructed, or
  145. you can do it earlier:
  146. ```cpp
  147. using ::testing::Mock;
  148. ...
  149. // Verifies and removes the expectations on mock_obj;
  150. // returns true if and only if successful.
  151. Mock::VerifyAndClearExpectations(&mock_obj);
  152. ...
  153. // Verifies and removes the expectations on mock_obj;
  154. // also removes the default actions set by ON_CALL();
  155. // returns true if and only if successful.
  156. Mock::VerifyAndClear(&mock_obj);
  157. ```
  158. Do not set new expectations after verifying and clearing a mock after its use.
  159. Setting expectations after code that exercises the mock has undefined behavior.
  160. See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more
  161. information.
  162. You can also tell gMock that a mock object can be leaked and doesn't need to be
  163. verified:
  164. ```cpp
  165. Mock::AllowLeak(&mock_obj);
  166. ```
  167. ## Mock Classes
  168. gMock defines a convenient mock class template
  169. ```cpp
  170. class MockFunction<R(A1, ..., An)> {
  171. public:
  172. MOCK_METHOD(R, Call, (A1, ..., An));
  173. };
  174. ```
  175. See this [recipe](gmock_cook_book.md#using-check-points) for one application of
  176. it.
  177. ## Flags
  178. | Flag | Description |
  179. | :----------------------------- | :---------------------------------------- |
  180. | `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
  181. | `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |