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.

396 lines
15 KiB

  1. ## Legacy gMock FAQ {#GMockFaq}
  2. <!-- GOOGLETEST_CM0021 DO NOT DELETE -->
  3. ### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem?
  4. In order for a method to be mocked, it must be *virtual*, unless you use the
  5. [high-perf dependency injection technique](#MockingNonVirtualMethods).
  6. ### Can I mock a variadic function?
  7. You cannot mock a variadic function (i.e. a function taking ellipsis (`...`)
  8. arguments) directly in gMock.
  9. The problem is that in general, there is *no way* for a mock object to know how
  10. many arguments are passed to the variadic method, and what the arguments' types
  11. are. Only the *author of the base class* knows the protocol, and we cannot look
  12. into his or her head.
  13. Therefore, to mock such a function, the *user* must teach the mock object how to
  14. figure out the number of arguments and their types. One way to do it is to
  15. provide overloaded versions of the function.
  16. Ellipsis arguments are inherited from C and not really a C++ feature. They are
  17. unsafe to use and don't work with arguments that have constructors or
  18. destructors. Therefore we recommend to avoid them in C++ as much as possible.
  19. ### MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why?
  20. If you compile this using Microsoft Visual C++ 2005 SP1:
  21. ```cpp
  22. class Foo {
  23. ...
  24. virtual void Bar(const int i) = 0;
  25. };
  26. class MockFoo : public Foo {
  27. ...
  28. MOCK_METHOD(void, Bar, (const int i), (override));
  29. };
  30. ```
  31. You may get the following warning:
  32. ```shell
  33. warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
  34. ```
  35. This is a MSVC bug. The same code compiles fine with gcc, for example. If you
  36. use Visual C++ 2008 SP1, you would get the warning:
  37. ```shell
  38. warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
  39. ```
  40. In C++, if you *declare* a function with a `const` parameter, the `const`
  41. modifier is ignored. Therefore, the `Foo` base class above is equivalent to:
  42. ```cpp
  43. class Foo {
  44. ...
  45. virtual void Bar(int i) = 0; // int or const int? Makes no difference.
  46. };
  47. ```
  48. In fact, you can *declare* `Bar()` with an `int` parameter, and define it with a
  49. `const int` parameter. The compiler will still match them up.
  50. Since making a parameter `const` is meaningless in the method declaration, we
  51. recommend to remove it in both `Foo` and `MockFoo`. That should workaround the
  52. VC bug.
  53. Note that we are talking about the *top-level* `const` modifier here. If the
  54. function parameter is passed by pointer or reference, declaring the pointee or
  55. referee as `const` is still meaningful. For example, the following two
  56. declarations are *not* equivalent:
  57. ```cpp
  58. void Bar(int* p); // Neither p nor *p is const.
  59. void Bar(const int* p); // p is not const, but *p is.
  60. ```
  61. <!-- GOOGLETEST_CM0030 DO NOT DELETE -->
  62. ### I can't figure out why gMock thinks my expectations are not satisfied. What should I do?
  63. You might want to run your test with `--gmock_verbose=info`. This flag lets
  64. gMock print a trace of every mock function call it receives. By studying the
  65. trace, you'll gain insights on why the expectations you set are not met.
  66. If you see the message "The mock function has no default action set, and its
  67. return type has no default value set.", then try
  68. [adding a default action](for_dummies.md#DefaultValue). Due to a known issue,
  69. unexpected calls on mocks without default actions don't print out a detailed
  70. comparison between the actual arguments and the expected arguments.
  71. ### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug?
  72. gMock and `ScopedMockLog` are likely doing the right thing here.
  73. When a test crashes, the failure signal handler will try to log a lot of
  74. information (the stack trace, and the address map, for example). The messages
  75. are compounded if you have many threads with depth stacks. When `ScopedMockLog`
  76. intercepts these messages and finds that they don't match any expectations, it
  77. prints an error for each of them.
  78. You can learn to ignore the errors, or you can rewrite your expectations to make
  79. your test more robust, for example, by adding something like:
  80. ```cpp
  81. using ::testing::AnyNumber;
  82. using ::testing::Not;
  83. ...
  84. // Ignores any log not done by us.
  85. EXPECT_CALL(log, Log(_, Not(EndsWith("/my_file.cc")), _))
  86. .Times(AnyNumber());
  87. ```
  88. ### How can I assert that a function is NEVER called?
  89. ```cpp
  90. using ::testing::_;
  91. ...
  92. EXPECT_CALL(foo, Bar(_))
  93. .Times(0);
  94. ```
  95. <!-- GOOGLETEST_CM0031 DO NOT DELETE -->
  96. ### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant?
  97. When gMock detects a failure, it prints relevant information (the mock function
  98. arguments, the state of relevant expectations, and etc) to help the user debug.
  99. If another failure is detected, gMock will do the same, including printing the
  100. state of relevant expectations.
  101. Sometimes an expectation's state didn't change between two failures, and you'll
  102. see the same description of the state twice. They are however *not* redundant,
  103. as they refer to *different points in time*. The fact they are the same *is*
  104. interesting information.
  105. ### I get a heapcheck failure when using a mock object, but using a real object is fine. What can be wrong?
  106. Does the class (hopefully a pure interface) you are mocking have a virtual
  107. destructor?
  108. Whenever you derive from a base class, make sure its destructor is virtual.
  109. Otherwise Bad Things will happen. Consider the following code:
  110. ```cpp
  111. class Base {
  112. public:
  113. // Not virtual, but should be.
  114. ~Base() { ... }
  115. ...
  116. };
  117. class Derived : public Base {
  118. public:
  119. ...
  120. private:
  121. std::string value_;
  122. };
  123. ...
  124. Base* p = new Derived;
  125. ...
  126. delete p; // Surprise! ~Base() will be called, but ~Derived() will not
  127. // - value_ is leaked.
  128. ```
  129. By changing `~Base()` to virtual, `~Derived()` will be correctly called when
  130. `delete p` is executed, and the heap checker will be happy.
  131. ### The "newer expectations override older ones" rule makes writing expectations awkward. Why does gMock do that?
  132. When people complain about this, often they are referring to code like:
  133. ```cpp
  134. using ::testing::Return;
  135. ...
  136. // foo.Bar() should be called twice, return 1 the first time, and return
  137. // 2 the second time. However, I have to write the expectations in the
  138. // reverse order. This sucks big time!!!
  139. EXPECT_CALL(foo, Bar())
  140. .WillOnce(Return(2))
  141. .RetiresOnSaturation();
  142. EXPECT_CALL(foo, Bar())
  143. .WillOnce(Return(1))
  144. .RetiresOnSaturation();
  145. ```
  146. The problem, is that they didn't pick the **best** way to express the test's
  147. intent.
  148. By default, expectations don't have to be matched in *any* particular order. If
  149. you want them to match in a certain order, you need to be explicit. This is
  150. gMock's (and jMock's) fundamental philosophy: it's easy to accidentally
  151. over-specify your tests, and we want to make it harder to do so.
  152. There are two better ways to write the test spec. You could either put the
  153. expectations in sequence:
  154. ```cpp
  155. using ::testing::Return;
  156. ...
  157. // foo.Bar() should be called twice, return 1 the first time, and return
  158. // 2 the second time. Using a sequence, we can write the expectations
  159. // in their natural order.
  160. {
  161. InSequence s;
  162. EXPECT_CALL(foo, Bar())
  163. .WillOnce(Return(1))
  164. .RetiresOnSaturation();
  165. EXPECT_CALL(foo, Bar())
  166. .WillOnce(Return(2))
  167. .RetiresOnSaturation();
  168. }
  169. ```
  170. or you can put the sequence of actions in the same expectation:
  171. ```cpp
  172. using ::testing::Return;
  173. ...
  174. // foo.Bar() should be called twice, return 1 the first time, and return
  175. // 2 the second time.
  176. EXPECT_CALL(foo, Bar())
  177. .WillOnce(Return(1))
  178. .WillOnce(Return(2))
  179. .RetiresOnSaturation();
  180. ```
  181. Back to the original questions: why does gMock search the expectations (and
  182. `ON_CALL`s) from back to front? Because this allows a user to set up a mock's
  183. behavior for the common case early (e.g. in the mock's constructor or the test
  184. fixture's set-up phase) and customize it with more specific rules later. If
  185. gMock searches from front to back, this very useful pattern won't be possible.
  186. ### gMock prints a warning when a function without EXPECT_CALL is called, even if I have set its behavior using ON_CALL. Would it be reasonable not to show the warning in this case?
  187. When choosing between being neat and being safe, we lean toward the latter. So
  188. the answer is that we think it's better to show the warning.
  189. Often people write `ON_CALL`s in the mock object's constructor or `SetUp()`, as
  190. the default behavior rarely changes from test to test. Then in the test body
  191. they set the expectations, which are often different for each test. Having an
  192. `ON_CALL` in the set-up part of a test doesn't mean that the calls are expected.
  193. If there's no `EXPECT_CALL` and the method is called, it's possibly an error. If
  194. we quietly let the call go through without notifying the user, bugs may creep in
  195. unnoticed.
  196. If, however, you are sure that the calls are OK, you can write
  197. ```cpp
  198. using ::testing::_;
  199. ...
  200. EXPECT_CALL(foo, Bar(_))
  201. .WillRepeatedly(...);
  202. ```
  203. instead of
  204. ```cpp
  205. using ::testing::_;
  206. ...
  207. ON_CALL(foo, Bar(_))
  208. .WillByDefault(...);
  209. ```
  210. This tells gMock that you do expect the calls and no warning should be printed.
  211. Also, you can control the verbosity by specifying `--gmock_verbose=error`. Other
  212. values are `info` and `warning`. If you find the output too noisy when
  213. debugging, just choose a less verbose level.
  214. ### How can I delete the mock function's argument in an action?
  215. If your mock function takes a pointer argument and you want to delete that
  216. argument, you can use testing::DeleteArg<N>() to delete the N'th (zero-indexed)
  217. argument:
  218. ```cpp
  219. using ::testing::_;
  220. ...
  221. MOCK_METHOD(void, Bar, (X* x, const Y& y));
  222. ...
  223. EXPECT_CALL(mock_foo_, Bar(_, _))
  224. .WillOnce(testing::DeleteArg<0>()));
  225. ```
  226. ### How can I perform an arbitrary action on a mock function's argument?
  227. If you find yourself needing to perform some action that's not supported by
  228. gMock directly, remember that you can define your own actions using
  229. [`MakeAction()`](#NewMonoActions) or
  230. [`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function
  231. and invoke it using [`Invoke()`](#FunctionsAsActions).
  232. ```cpp
  233. using ::testing::_;
  234. using ::testing::Invoke;
  235. ...
  236. MOCK_METHOD(void, Bar, (X* p));
  237. ...
  238. EXPECT_CALL(mock_foo_, Bar(_))
  239. .WillOnce(Invoke(MyAction(...)));
  240. ```
  241. ### My code calls a static/global function. Can I mock it?
  242. You can, but you need to make some changes.
  243. In general, if you find yourself needing to mock a static function, it's a sign
  244. that your modules are too tightly coupled (and less flexible, less reusable,
  245. less testable, etc). You are probably better off defining a small interface and
  246. call the function through that interface, which then can be easily mocked. It's
  247. a bit of work initially, but usually pays for itself quickly.
  248. This Google Testing Blog
  249. [post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it
  250. excellently. Check it out.
  251. ### My mock object needs to do complex stuff. It's a lot of pain to specify the actions. gMock sucks!
  252. I know it's not a question, but you get an answer for free any way. :-)
  253. With gMock, you can create mocks in C++ easily. And people might be tempted to
  254. use them everywhere. Sometimes they work great, and sometimes you may find them,
  255. well, a pain to use. So, what's wrong in the latter case?
  256. When you write a test without using mocks, you exercise the code and assert that
  257. it returns the correct value or that the system is in an expected state. This is
  258. sometimes called "state-based testing".
  259. Mocks are great for what some call "interaction-based" testing: instead of
  260. checking the system state at the very end, mock objects verify that they are
  261. invoked the right way and report an error as soon as it arises, giving you a
  262. handle on the precise context in which the error was triggered. This is often
  263. more effective and economical to do than state-based testing.
  264. If you are doing state-based testing and using a test double just to simulate
  265. the real object, you are probably better off using a fake. Using a mock in this
  266. case causes pain, as it's not a strong point for mocks to perform complex
  267. actions. If you experience this and think that mocks suck, you are just not
  268. using the right tool for your problem. Or, you might be trying to solve the
  269. wrong problem. :-)
  270. ### I got a warning "Uninteresting function call encountered - default action taken.." Should I panic?
  271. By all means, NO! It's just an FYI. :-)
  272. What it means is that you have a mock function, you haven't set any expectations
  273. on it (by gMock's rule this means that you are not interested in calls to this
  274. function and therefore it can be called any number of times), and it is called.
  275. That's OK - you didn't say it's not OK to call the function!
  276. What if you actually meant to disallow this function to be called, but forgot to
  277. write `EXPECT_CALL(foo, Bar()).Times(0)`? While one can argue that it's the
  278. user's fault, gMock tries to be nice and prints you a note.
  279. So, when you see the message and believe that there shouldn't be any
  280. uninteresting calls, you should investigate what's going on. To make your life
  281. easier, gMock dumps the stack trace when an uninteresting call is encountered.
  282. From that you can figure out which mock function it is, and how it is called.
  283. ### I want to define a custom action. Should I use Invoke() or implement the ActionInterface interface?
  284. Either way is fine - you want to choose the one that's more convenient for your
  285. circumstance.
  286. Usually, if your action is for a particular function type, defining it using
  287. `Invoke()` should be easier; if your action can be used in functions of
  288. different types (e.g. if you are defining `Return(*value*)`),
  289. `MakePolymorphicAction()` is easiest. Sometimes you want precise control on what
  290. types of functions the action can be used in, and implementing `ActionInterface`
  291. is the way to go here. See the implementation of `Return()` in
  292. `testing/base/public/gmock-actions.h` for an example.
  293. ### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean?
  294. You got this error as gMock has no idea what value it should return when the
  295. mock method is called. `SetArgPointee()` says what the side effect is, but
  296. doesn't say what the return value should be. You need `DoAll()` to chain a
  297. `SetArgPointee()` with a `Return()` that provides a value appropriate to the API
  298. being mocked.
  299. See this [recipe](cook_book.md#mocking-side-effects) for more details and an
  300. example.
  301. ### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do?
  302. We've noticed that when the `/clr` compiler flag is used, Visual C++ uses 5~6
  303. times as much memory when compiling a mock class. We suggest to avoid `/clr`
  304. when compiling native C++ mocks.