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.

587 lines
20 KiB

2 months ago
  1. # Mocking Reference
  2. This page lists the facilities provided by GoogleTest for creating and working
  3. with mock objects. To use them, include the header
  4. `gmock/gmock.h`.
  5. ## Macros {#macros}
  6. GoogleTest defines the following macros for working with mocks.
  7. ### MOCK_METHOD {#MOCK_METHOD}
  8. `MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`));` \
  9. `MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`),
  10. (`*`specs...`*`));`
  11. Defines a mock method *`method_name`* with arguments `(`*`args...`*`)` and
  12. return type *`return_type`* within a mock class.
  13. The parameters of `MOCK_METHOD` mirror the method declaration. The optional
  14. fourth parameter *`specs...`* is a comma-separated list of qualifiers. The
  15. following qualifiers are accepted:
  16. | Qualifier | Meaning |
  17. | -------------------------- | -------------------------------------------- |
  18. | `const` | Makes the mocked method a `const` method. Required if overriding a `const` method. |
  19. | `override` | Marks the method with `override`. Recommended if overriding a `virtual` method. |
  20. | `noexcept` | Marks the method with `noexcept`. Required if overriding a `noexcept` method. |
  21. | `Calltype(`*`calltype`*`)` | Sets the call type for the method, for example `Calltype(STDMETHODCALLTYPE)`. Useful on Windows. |
  22. | `ref(`*`qualifier`*`)` | Marks the method with the given reference qualifier, for example `ref(&)` or `ref(&&)`. Required if overriding a method that has a reference qualifier. |
  23. Note that commas in arguments prevent `MOCK_METHOD` from parsing the arguments
  24. correctly if they are not appropriately surrounded by parentheses. See the
  25. following example:
  26. ```cpp
  27. class MyMock {
  28. public:
  29. // The following 2 lines will not compile due to commas in the arguments:
  30. MOCK_METHOD(std::pair<bool, int>, GetPair, ()); // Error!
  31. MOCK_METHOD(bool, CheckMap, (std::map<int, double>, bool)); // Error!
  32. // One solution - wrap arguments that contain commas in parentheses:
  33. MOCK_METHOD((std::pair<bool, int>), GetPair, ());
  34. MOCK_METHOD(bool, CheckMap, ((std::map<int, double>), bool));
  35. // Another solution - use type aliases:
  36. using BoolAndInt = std::pair<bool, int>;
  37. MOCK_METHOD(BoolAndInt, GetPair, ());
  38. using MapIntDouble = std::map<int, double>;
  39. MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool));
  40. };
  41. ```
  42. `MOCK_METHOD` must be used in the `public:` section of a mock class definition,
  43. regardless of whether the method being mocked is `public`, `protected`, or
  44. `private` in the base class.
  45. ### EXPECT_CALL {#EXPECT_CALL}
  46. `EXPECT_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`
  47. Creates an [expectation](../gmock_for_dummies.md#setting-expectations) that the
  48. method *`method_name`* of the object *`mock_object`* is called with arguments
  49. that match the given matchers *`matchers...`*. `EXPECT_CALL` must precede any
  50. code that exercises the mock object.
  51. The parameter *`matchers...`* is a comma-separated list of
  52. [matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that
  53. correspond to each argument of the method *`method_name`*. The expectation will
  54. apply only to calls of *`method_name`* whose arguments match all of the
  55. matchers. If `(`*`matchers...`*`)` is omitted, the expectation behaves as if
  56. each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).
  57. See the [Matchers Reference](matchers.md) for a list of all built-in matchers.
  58. The following chainable clauses can be used to modify the expectation, and they
  59. must be used in the following order:
  60. ```cpp
  61. EXPECT_CALL(mock_object, method_name(matchers...))
  62. .With(multi_argument_matcher) // Can be used at most once
  63. .Times(cardinality) // Can be used at most once
  64. .InSequence(sequences...) // Can be used any number of times
  65. .After(expectations...) // Can be used any number of times
  66. .WillOnce(action) // Can be used any number of times
  67. .WillRepeatedly(action) // Can be used at most once
  68. .RetiresOnSaturation(); // Can be used at most once
  69. ```
  70. See details for each modifier clause below.
  71. #### With {#EXPECT_CALL.With}
  72. `.With(`*`multi_argument_matcher`*`)`
  73. Restricts the expectation to apply only to mock function calls whose arguments
  74. as a whole match the multi-argument matcher *`multi_argument_matcher`*.
  75. GoogleTest passes all of the arguments as one tuple into the matcher. The
  76. parameter *`multi_argument_matcher`* must thus be a matcher of type
  77. `Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the
  78. function arguments.
  79. For example, the following code sets the expectation that
  80. `my_mock.SetPosition()` is called with any two arguments, the first argument
  81. being less than the second:
  82. ```cpp
  83. using ::testing::_;
  84. using ::testing::Lt;
  85. ...
  86. EXPECT_CALL(my_mock, SetPosition(_, _))
  87. .With(Lt());
  88. ```
  89. GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`
  90. matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).
  91. The `With` clause can be used at most once on an expectation and must be the
  92. first clause.
  93. #### Times {#EXPECT_CALL.Times}
  94. `.Times(`*`cardinality`*`)`
  95. Specifies how many times the mock function call is expected.
  96. The parameter *`cardinality`* represents the number of expected calls and can be
  97. one of the following, all defined in the `::testing` namespace:
  98. | Cardinality | Meaning |
  99. | ------------------- | --------------------------------------------------- |
  100. | `AnyNumber()` | The function can be called any number of times. |
  101. | `AtLeast(n)` | The function call is expected at least *n* times. |
  102. | `AtMost(n)` | The function call is expected at most *n* times. |
  103. | `Between(m, n)` | The function call is expected between *m* and *n* times, inclusive. |
  104. | `Exactly(n)` or `n` | The function call is expected exactly *n* times. If *n* is 0, the call should never happen. |
  105. If the `Times` clause is omitted, GoogleTest infers the cardinality as follows:
  106. * If neither [`WillOnce`](#EXPECT_CALL.WillOnce) nor
  107. [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) are specified, the inferred
  108. cardinality is `Times(1)`.
  109. * If there are *n* `WillOnce` clauses and no `WillRepeatedly` clause, where
  110. *n* >= 1, the inferred cardinality is `Times(n)`.
  111. * If there are *n* `WillOnce` clauses and one `WillRepeatedly` clause, where
  112. *n* >= 0, the inferred cardinality is `Times(AtLeast(n))`.
  113. The `Times` clause can be used at most once on an expectation.
  114. #### InSequence {#EXPECT_CALL.InSequence}
  115. `.InSequence(`*`sequences...`*`)`
  116. Specifies that the mock function call is expected in a certain sequence.
  117. The parameter *`sequences...`* is any number of [`Sequence`](#Sequence) objects.
  118. Expected calls assigned to the same sequence are expected to occur in the order
  119. the expectations are declared.
  120. For example, the following code sets the expectation that the `Reset()` method
  121. of `my_mock` is called before both `GetSize()` and `Describe()`, and `GetSize()`
  122. and `Describe()` can occur in any order relative to each other:
  123. ```cpp
  124. using ::testing::Sequence;
  125. Sequence s1, s2;
  126. ...
  127. EXPECT_CALL(my_mock, Reset())
  128. .InSequence(s1, s2);
  129. EXPECT_CALL(my_mock, GetSize())
  130. .InSequence(s1);
  131. EXPECT_CALL(my_mock, Describe())
  132. .InSequence(s2);
  133. ```
  134. The `InSequence` clause can be used any number of times on an expectation.
  135. See also the [`InSequence` class](#InSequence).
  136. #### After {#EXPECT_CALL.After}
  137. `.After(`*`expectations...`*`)`
  138. Specifies that the mock function call is expected to occur after one or more
  139. other calls.
  140. The parameter *`expectations...`* can be up to five
  141. [`Expectation`](#Expectation) or [`ExpectationSet`](#ExpectationSet) objects.
  142. The mock function call is expected to occur after all of the given expectations.
  143. For example, the following code sets the expectation that the `Describe()`
  144. method of `my_mock` is called only after both `InitX()` and `InitY()` have been
  145. called.
  146. ```cpp
  147. using ::testing::Expectation;
  148. ...
  149. Expectation init_x = EXPECT_CALL(my_mock, InitX());
  150. Expectation init_y = EXPECT_CALL(my_mock, InitY());
  151. EXPECT_CALL(my_mock, Describe())
  152. .After(init_x, init_y);
  153. ```
  154. The `ExpectationSet` object is helpful when the number of prerequisites for an
  155. expectation is large or variable, for example:
  156. ```cpp
  157. using ::testing::ExpectationSet;
  158. ...
  159. ExpectationSet all_inits;
  160. // Collect all expectations of InitElement() calls
  161. for (int i = 0; i < element_count; i++) {
  162. all_inits += EXPECT_CALL(my_mock, InitElement(i));
  163. }
  164. EXPECT_CALL(my_mock, Describe())
  165. .After(all_inits); // Expect Describe() call after all InitElement() calls
  166. ```
  167. The `After` clause can be used any number of times on an expectation.
  168. #### WillOnce {#EXPECT_CALL.WillOnce}
  169. `.WillOnce(`*`action`*`)`
  170. Specifies the mock function's actual behavior when invoked, for a single
  171. matching function call.
  172. The parameter *`action`* represents the
  173. [action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
  174. call will perform. See the [Actions Reference](actions.md) for a list of
  175. built-in actions.
  176. The use of `WillOnce` implicitly sets a cardinality on the expectation when
  177. `Times` is not specified. See [`Times`](#EXPECT_CALL.Times).
  178. Each matching function call will perform the next action in the order declared.
  179. For example, the following code specifies that `my_mock.GetNumber()` is expected
  180. to be called exactly 3 times and will return `1`, `2`, and `3` respectively on
  181. the first, second, and third calls:
  182. ```cpp
  183. using ::testing::Return;
  184. ...
  185. EXPECT_CALL(my_mock, GetNumber())
  186. .WillOnce(Return(1))
  187. .WillOnce(Return(2))
  188. .WillOnce(Return(3));
  189. ```
  190. The `WillOnce` clause can be used any number of times on an expectation.
  191. #### WillRepeatedly {#EXPECT_CALL.WillRepeatedly}
  192. `.WillRepeatedly(`*`action`*`)`
  193. Specifies the mock function's actual behavior when invoked, for all subsequent
  194. matching function calls. Takes effect after the actions specified in the
  195. [`WillOnce`](#EXPECT_CALL.WillOnce) clauses, if any, have been performed.
  196. The parameter *`action`* represents the
  197. [action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
  198. call will perform. See the [Actions Reference](actions.md) for a list of
  199. built-in actions.
  200. The use of `WillRepeatedly` implicitly sets a cardinality on the expectation
  201. when `Times` is not specified. See [`Times`](#EXPECT_CALL.Times).
  202. If any `WillOnce` clauses have been specified, matching function calls will
  203. perform those actions before the action specified by `WillRepeatedly`. See the
  204. following example:
  205. ```cpp
  206. using ::testing::Return;
  207. ...
  208. EXPECT_CALL(my_mock, GetName())
  209. .WillRepeatedly(Return("John Doe")); // Return "John Doe" on all calls
  210. EXPECT_CALL(my_mock, GetNumber())
  211. .WillOnce(Return(42)) // Return 42 on the first call
  212. .WillRepeatedly(Return(7)); // Return 7 on all subsequent calls
  213. ```
  214. The `WillRepeatedly` clause can be used at most once on an expectation.
  215. #### RetiresOnSaturation {#EXPECT_CALL.RetiresOnSaturation}
  216. `.RetiresOnSaturation()`
  217. Indicates that the expectation will no longer be active after the expected
  218. number of matching function calls has been reached.
  219. The `RetiresOnSaturation` clause is only meaningful for expectations with an
  220. upper-bounded cardinality. The expectation will *retire* (no longer match any
  221. function calls) after it has been *saturated* (the upper bound has been
  222. reached). See the following example:
  223. ```cpp
  224. using ::testing::_;
  225. using ::testing::AnyNumber;
  226. ...
  227. EXPECT_CALL(my_mock, SetNumber(_)) // Expectation 1
  228. .Times(AnyNumber());
  229. EXPECT_CALL(my_mock, SetNumber(7)) // Expectation 2
  230. .Times(2)
  231. .RetiresOnSaturation();
  232. ```
  233. In the above example, the first two calls to `my_mock.SetNumber(7)` match
  234. expectation 2, which then becomes inactive and no longer matches any calls. A
  235. third call to `my_mock.SetNumber(7)` would then match expectation 1. Without
  236. `RetiresOnSaturation()` on expectation 2, a third call to `my_mock.SetNumber(7)`
  237. would match expectation 2 again, producing a failure since the limit of 2 calls
  238. was exceeded.
  239. The `RetiresOnSaturation` clause can be used at most once on an expectation and
  240. must be the last clause.
  241. ### ON_CALL {#ON_CALL}
  242. `ON_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`
  243. Defines what happens when the method *`method_name`* of the object
  244. *`mock_object`* is called with arguments that match the given matchers
  245. *`matchers...`*. Requires a modifier clause to specify the method's behavior.
  246. *Does not* set any expectations that the method will be called.
  247. The parameter *`matchers...`* is a comma-separated list of
  248. [matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that
  249. correspond to each argument of the method *`method_name`*. The `ON_CALL`
  250. specification will apply only to calls of *`method_name`* whose arguments match
  251. all of the matchers. If `(`*`matchers...`*`)` is omitted, the behavior is as if
  252. each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).
  253. See the [Matchers Reference](matchers.md) for a list of all built-in matchers.
  254. The following chainable clauses can be used to set the method's behavior, and
  255. they must be used in the following order:
  256. ```cpp
  257. ON_CALL(mock_object, method_name(matchers...))
  258. .With(multi_argument_matcher) // Can be used at most once
  259. .WillByDefault(action); // Required
  260. ```
  261. See details for each modifier clause below.
  262. #### With {#ON_CALL.With}
  263. `.With(`*`multi_argument_matcher`*`)`
  264. Restricts the specification to only mock function calls whose arguments as a
  265. whole match the multi-argument matcher *`multi_argument_matcher`*.
  266. GoogleTest passes all of the arguments as one tuple into the matcher. The
  267. parameter *`multi_argument_matcher`* must thus be a matcher of type
  268. `Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the
  269. function arguments.
  270. For example, the following code sets the default behavior when
  271. `my_mock.SetPosition()` is called with any two arguments, the first argument
  272. being less than the second:
  273. ```cpp
  274. using ::testing::_;
  275. using ::testing::Lt;
  276. using ::testing::Return;
  277. ...
  278. ON_CALL(my_mock, SetPosition(_, _))
  279. .With(Lt())
  280. .WillByDefault(Return(true));
  281. ```
  282. GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`
  283. matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).
  284. The `With` clause can be used at most once with each `ON_CALL` statement.
  285. #### WillByDefault {#ON_CALL.WillByDefault}
  286. `.WillByDefault(`*`action`*`)`
  287. Specifies the default behavior of a matching mock function call.
  288. The parameter *`action`* represents the
  289. [action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
  290. call will perform. See the [Actions Reference](actions.md) for a list of
  291. built-in actions.
  292. For example, the following code specifies that by default, a call to
  293. `my_mock.Greet()` will return `"hello"`:
  294. ```cpp
  295. using ::testing::Return;
  296. ...
  297. ON_CALL(my_mock, Greet())
  298. .WillByDefault(Return("hello"));
  299. ```
  300. The action specified by `WillByDefault` is superseded by the actions specified
  301. on a matching `EXPECT_CALL` statement, if any. See the
  302. [`WillOnce`](#EXPECT_CALL.WillOnce) and
  303. [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) clauses of `EXPECT_CALL`.
  304. The `WillByDefault` clause must be used exactly once with each `ON_CALL`
  305. statement.
  306. ## Classes {#classes}
  307. GoogleTest defines the following classes for working with mocks.
  308. ### DefaultValue {#DefaultValue}
  309. `::testing::DefaultValue<T>`
  310. Allows a user to specify the default value for a type `T` that is both copyable
  311. and publicly destructible (i.e. anything that can be used as a function return
  312. type). For mock functions with a return type of `T`, this default value is
  313. returned from function calls that do not specify an action.
  314. Provides the static methods `Set()`, `SetFactory()`, and `Clear()` to manage the
  315. default value:
  316. ```cpp
  317. // Sets the default value to be returned. T must be copy constructible.
  318. DefaultValue<T>::Set(value);
  319. // Sets a factory. Will be invoked on demand. T must be move constructible.
  320. T MakeT();
  321. DefaultValue<T>::SetFactory(&MakeT);
  322. // Unsets the default value.
  323. DefaultValue<T>::Clear();
  324. ```
  325. ### NiceMock {#NiceMock}
  326. `::testing::NiceMock<T>`
  327. Represents a mock object that suppresses warnings on
  328. [uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
  329. template parameter `T` is any mock class, except for another `NiceMock`,
  330. `NaggyMock`, or `StrictMock`.
  331. Usage of `NiceMock<T>` is analogous to usage of `T`. `NiceMock<T>` is a subclass
  332. of `T`, so it can be used wherever an object of type `T` is accepted. In
  333. addition, `NiceMock<T>` can be constructed with any arguments that a constructor
  334. of `T` accepts.
  335. For example, the following code suppresses warnings on the mock `my_mock` of
  336. type `MockClass` if a method other than `DoSomething()` is called:
  337. ```cpp
  338. using ::testing::NiceMock;
  339. ...
  340. NiceMock<MockClass> my_mock("some", "args");
  341. EXPECT_CALL(my_mock, DoSomething());
  342. ... code that uses my_mock ...
  343. ```
  344. `NiceMock<T>` only works for mock methods defined using the `MOCK_METHOD` macro
  345. directly in the definition of class `T`. If a mock method is defined in a base
  346. class of `T`, a warning might still be generated.
  347. `NiceMock<T>` might not work correctly if the destructor of `T` is not virtual.
  348. ### NaggyMock {#NaggyMock}
  349. `::testing::NaggyMock<T>`
  350. Represents a mock object that generates warnings on
  351. [uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
  352. template parameter `T` is any mock class, except for another `NiceMock`,
  353. `NaggyMock`, or `StrictMock`.
  354. Usage of `NaggyMock<T>` is analogous to usage of `T`. `NaggyMock<T>` is a
  355. subclass of `T`, so it can be used wherever an object of type `T` is accepted.
  356. In addition, `NaggyMock<T>` can be constructed with any arguments that a
  357. constructor of `T` accepts.
  358. For example, the following code generates warnings on the mock `my_mock` of type
  359. `MockClass` if a method other than `DoSomething()` is called:
  360. ```cpp
  361. using ::testing::NaggyMock;
  362. ...
  363. NaggyMock<MockClass> my_mock("some", "args");
  364. EXPECT_CALL(my_mock, DoSomething());
  365. ... code that uses my_mock ...
  366. ```
  367. Mock objects of type `T` by default behave the same way as `NaggyMock<T>`.
  368. ### StrictMock {#StrictMock}
  369. `::testing::StrictMock<T>`
  370. Represents a mock object that generates test failures on
  371. [uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
  372. template parameter `T` is any mock class, except for another `NiceMock`,
  373. `NaggyMock`, or `StrictMock`.
  374. Usage of `StrictMock<T>` is analogous to usage of `T`. `StrictMock<T>` is a
  375. subclass of `T`, so it can be used wherever an object of type `T` is accepted.
  376. In addition, `StrictMock<T>` can be constructed with any arguments that a
  377. constructor of `T` accepts.
  378. For example, the following code generates a test failure on the mock `my_mock`
  379. of type `MockClass` if a method other than `DoSomething()` is called:
  380. ```cpp
  381. using ::testing::StrictMock;
  382. ...
  383. StrictMock<MockClass> my_mock("some", "args");
  384. EXPECT_CALL(my_mock, DoSomething());
  385. ... code that uses my_mock ...
  386. ```
  387. `StrictMock<T>` only works for mock methods defined using the `MOCK_METHOD`
  388. macro directly in the definition of class `T`. If a mock method is defined in a
  389. base class of `T`, a failure might not be generated.
  390. `StrictMock<T>` might not work correctly if the destructor of `T` is not
  391. virtual.
  392. ### Sequence {#Sequence}
  393. `::testing::Sequence`
  394. Represents a chronological sequence of expectations. See the
  395. [`InSequence`](#EXPECT_CALL.InSequence) clause of `EXPECT_CALL` for usage.
  396. ### InSequence {#InSequence}
  397. `::testing::InSequence`
  398. An object of this type causes all expectations encountered in its scope to be
  399. put in an anonymous sequence.
  400. This allows more convenient expression of multiple expectations in a single
  401. sequence:
  402. ```cpp
  403. using ::testing::InSequence;
  404. {
  405. InSequence seq;
  406. // The following are expected to occur in the order declared.
  407. EXPECT_CALL(...);
  408. EXPECT_CALL(...);
  409. ...
  410. EXPECT_CALL(...);
  411. }
  412. ```
  413. The name of the `InSequence` object does not matter.
  414. ### Expectation {#Expectation}
  415. `::testing::Expectation`
  416. Represents a mock function call expectation as created by
  417. [`EXPECT_CALL`](#EXPECT_CALL):
  418. ```cpp
  419. using ::testing::Expectation;
  420. Expectation my_expectation = EXPECT_CALL(...);
  421. ```
  422. Useful for specifying sequences of expectations; see the
  423. [`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.
  424. ### ExpectationSet {#ExpectationSet}
  425. `::testing::ExpectationSet`
  426. Represents a set of mock function call expectations.
  427. Use the `+=` operator to add [`Expectation`](#Expectation) objects to the set:
  428. ```cpp
  429. using ::testing::ExpectationSet;
  430. ExpectationSet my_expectations;
  431. my_expectations += EXPECT_CALL(...);
  432. ```
  433. Useful for specifying sequences of expectations; see the
  434. [`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.