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.

373 lines
11 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`*:
  104. ```cpp
  105. using ::testing::DefaultValue;
  106. // Sets the default value to be returned. T must be CopyConstructible.
  107. DefaultValue<T>::Set(value);
  108. // Sets a factory. Will be invoked on demand. T must be MoveConstructible.
  109. // T MakeT();
  110. DefaultValue<T>::SetFactory(&MakeT);
  111. // ... use the mocks ...
  112. // Resets the default value.
  113. DefaultValue<T>::Clear();
  114. ```
  115. Example usage:
  116. ```cpp
  117. // Sets the default action for return type std::unique_ptr<Buzz> to
  118. // creating a new Buzz every time.
  119. DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
  120. [] { return MakeUnique<Buzz>(AccessLevel::kInternal); });
  121. // When this fires, the default action of MakeBuzz() will run, which
  122. // will return a new Buzz object.
  123. EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
  124. auto buzz1 = mock_buzzer_.MakeBuzz("hello");
  125. auto buzz2 = mock_buzzer_.MakeBuzz("hello");
  126. EXPECT_NE(buzz1, nullptr);
  127. EXPECT_NE(buzz2, nullptr);
  128. EXPECT_NE(buzz1, buzz2);
  129. // Resets the default action for return type std::unique_ptr<Buzz>,
  130. // to avoid interfere with other tests.
  131. DefaultValue<std::unique_ptr<Buzz>>::Clear();
  132. ```
  133. To customize the default action for a particular method of a specific mock
  134. object, use `ON_CALL()`. `ON_CALL()` has a similar syntax to `EXPECT_CALL()`,
  135. but it is used for setting default behaviors (when you do not require that the
  136. mock method is called). See [here](gmock_cook_book.md#UseOnCall) for a more
  137. detailed discussion.
  138. ```cpp
  139. ON_CALL(mock-object, method(matchers))
  140. .With(multi-argument-matcher) ?
  141. .WillByDefault(action);
  142. ```
  143. ## Setting Expectations {#ExpectCall}
  144. `EXPECT_CALL()` sets **expectations** on a mock method (How will it be called?
  145. What will it do?):
  146. ```cpp
  147. EXPECT_CALL(mock-object, method (matchers)?)
  148. .With(multi-argument-matcher) ?
  149. .Times(cardinality) ?
  150. .InSequence(sequences) *
  151. .After(expectations) *
  152. .WillOnce(action) *
  153. .WillRepeatedly(action) ?
  154. .RetiresOnSaturation(); ?
  155. ```
  156. For each item above, `?` means it can be used at most once, while `*` means it
  157. can be used any number of times.
  158. In order to pass, `EXPECT_CALL` must be used before the calls are actually made.
  159. The `(matchers)` is a comma-separated list of matchers that correspond to each
  160. of the arguments of `method`, and sets the expectation only for calls of
  161. `method` that matches all of the matchers.
  162. If `(matchers)` is omitted, the expectation is the same as if the matchers were
  163. set to anything matchers (for example, `(_, _, _, _)` for a four-arg method).
  164. If `Times()` is omitted, the cardinality is assumed to be:
  165. * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`;
  166. * `Times(n)` when there are `n` `WillOnce()`s but no `WillRepeatedly()`, where
  167. `n` >= 1; or
  168. * `Times(AtLeast(n))` when there are `n` `WillOnce()`s and a
  169. `WillRepeatedly()`, where `n` >= 0.
  170. A method with no `EXPECT_CALL()` is free to be invoked *any number of times*,
  171. and the default action will be taken each time.
  172. ## Matchers {#MatcherList}
  173. See the [Matchers Reference](reference/matchers.md).
  174. ## Actions {#ActionList}
  175. See the [Actions Reference](reference/actions.md).
  176. ## Cardinalities {#CardinalityList}
  177. These are used in `Times()` to specify how many times a mock function will be
  178. called:
  179. | | |
  180. | :---------------- | :----------------------------------------------------- |
  181. | `AnyNumber()` | The function can be called any number of times. |
  182. | `AtLeast(n)` | The call is expected at least `n` times. |
  183. | `AtMost(n)` | The call is expected at most `n` times. |
  184. | `Between(m, n)` | The call is expected between `m` and `n` (inclusive) times. |
  185. | `Exactly(n) or n` | The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0. |
  186. ## Expectation Order
  187. By default, the expectations can be matched in *any* order. If some or all
  188. expectations must be matched in a given order, there are two ways to specify it.
  189. They can be used either independently or together.
  190. ### The After Clause {#AfterClause}
  191. ```cpp
  192. using ::testing::Expectation;
  193. ...
  194. Expectation init_x = EXPECT_CALL(foo, InitX());
  195. Expectation init_y = EXPECT_CALL(foo, InitY());
  196. EXPECT_CALL(foo, Bar())
  197. .After(init_x, init_y);
  198. ```
  199. says that `Bar()` can be called only after both `InitX()` and `InitY()` have
  200. been called.
  201. If you don't know how many pre-requisites an expectation has when you write it,
  202. you can use an `ExpectationSet` to collect them:
  203. ```cpp
  204. using ::testing::ExpectationSet;
  205. ...
  206. ExpectationSet all_inits;
  207. for (int i = 0; i < element_count; i++) {
  208. all_inits += EXPECT_CALL(foo, InitElement(i));
  209. }
  210. EXPECT_CALL(foo, Bar())
  211. .After(all_inits);
  212. ```
  213. says that `Bar()` can be called only after all elements have been initialized
  214. (but we don't care about which elements get initialized before the others).
  215. Modifying an `ExpectationSet` after using it in an `.After()` doesn't affect the
  216. meaning of the `.After()`.
  217. ### Sequences {#UsingSequences}
  218. When you have a long chain of sequential expectations, it's easier to specify
  219. the order using **sequences**, which don't require you to give each expectation
  220. in the chain a different name. *All expected calls* in the same sequence must
  221. occur in the order they are specified.
  222. ```cpp
  223. using ::testing::Return;
  224. using ::testing::Sequence;
  225. Sequence s1, s2;
  226. ...
  227. EXPECT_CALL(foo, Reset())
  228. .InSequence(s1, s2)
  229. .WillOnce(Return(true));
  230. EXPECT_CALL(foo, GetSize())
  231. .InSequence(s1)
  232. .WillOnce(Return(1));
  233. EXPECT_CALL(foo, Describe(A<const char*>()))
  234. .InSequence(s2)
  235. .WillOnce(Return("dummy"));
  236. ```
  237. says that `Reset()` must be called before *both* `GetSize()` *and* `Describe()`,
  238. and the latter two can occur in any order.
  239. To put many expectations in a sequence conveniently:
  240. ```cpp
  241. using ::testing::InSequence;
  242. {
  243. InSequence seq;
  244. EXPECT_CALL(...)...;
  245. EXPECT_CALL(...)...;
  246. ...
  247. EXPECT_CALL(...)...;
  248. }
  249. ```
  250. says that all expected calls in the scope of `seq` must occur in strict order.
  251. The name `seq` is irrelevant.
  252. ## Verifying and Resetting a Mock
  253. gMock will verify the expectations on a mock object when it is destructed, or
  254. you can do it earlier:
  255. ```cpp
  256. using ::testing::Mock;
  257. ...
  258. // Verifies and removes the expectations on mock_obj;
  259. // returns true if and only if successful.
  260. Mock::VerifyAndClearExpectations(&mock_obj);
  261. ...
  262. // Verifies and removes the expectations on mock_obj;
  263. // also removes the default actions set by ON_CALL();
  264. // returns true if and only if successful.
  265. Mock::VerifyAndClear(&mock_obj);
  266. ```
  267. You can also tell gMock that a mock object can be leaked and doesn't need to be
  268. verified:
  269. ```cpp
  270. Mock::AllowLeak(&mock_obj);
  271. ```
  272. ## Mock Classes
  273. gMock defines a convenient mock class template
  274. ```cpp
  275. class MockFunction<R(A1, ..., An)> {
  276. public:
  277. MOCK_METHOD(R, Call, (A1, ..., An));
  278. };
  279. ```
  280. See this [recipe](gmock_cook_book.md#using-check-points) for one application of
  281. it.
  282. ## Flags
  283. | Flag | Description |
  284. | :----------------------------- | :---------------------------------------- |
  285. | `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
  286. | `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |