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.

753 lines
31 KiB

  1. # Googletest FAQ
  2. <!-- GOOGLETEST_CM0014 DO NOT DELETE -->
  3. ## Why should test suite names and test names not contain underscore?
  4. Underscore (`_`) is special, as C++ reserves the following to be used by the
  5. compiler and the standard library:
  6. 1. any identifier that starts with an `_` followed by an upper-case letter, and
  7. 2. any identifier that contains two consecutive underscores (i.e. `__`)
  8. *anywhere* in its name.
  9. User code is *prohibited* from using such identifiers.
  10. Now let's look at what this means for `TEST` and `TEST_F`.
  11. Currently `TEST(TestSuiteName, TestName)` generates a class named
  12. `TestSuiteName_TestName_Test`. What happens if `TestSuiteName` or `TestName`
  13. contains `_`?
  14. 1. If `TestSuiteName` starts with an `_` followed by an upper-case letter (say,
  15. `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus
  16. invalid.
  17. 2. If `TestSuiteName` ends with an `_` (say, `Foo_`), we get
  18. `Foo__TestName_Test`, which is invalid.
  19. 3. If `TestName` starts with an `_` (say, `_Bar`), we get
  20. `TestSuiteName__Bar_Test`, which is invalid.
  21. 4. If `TestName` ends with an `_` (say, `Bar_`), we get
  22. `TestSuiteName_Bar__Test`, which is invalid.
  23. So clearly `TestSuiteName` and `TestName` cannot start or end with `_`
  24. (Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't
  25. followed by an upper-case letter. But that's getting complicated. So for
  26. simplicity we just say that it cannot start with `_`.).
  27. It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the
  28. middle. However, consider this:
  29. ```c++
  30. TEST(Time, Flies_Like_An_Arrow) { ... }
  31. TEST(Time_Flies, Like_An_Arrow) { ... }
  32. ```
  33. Now, the two `TEST`s will both generate the same class
  34. (`Time_Flies_Like_An_Arrow_Test`). That's not good.
  35. So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and
  36. `TestName`. The rule is more constraining than necessary, but it's simple and
  37. easy to remember. It also gives googletest some wiggle room in case its
  38. implementation needs to change in the future.
  39. If you violate the rule, there may not be immediate consequences, but your test
  40. may (just may) break with a new compiler (or a new version of the compiler you
  41. are using) or with a new version of googletest. Therefore it's best to follow
  42. the rule.
  43. ## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
  44. First of all you can use `EXPECT_NE(nullptr, ptr)` and `ASSERT_NE(nullptr,
  45. ptr)`. This is the preferred syntax in the style guide because nullptr does not
  46. have the type problems that NULL does. Which is why NULL does not work.
  47. Due to some peculiarity of C++, it requires some non-trivial template meta
  48. programming tricks to support using `NULL` as an argument of the `EXPECT_XX()`
  49. and `ASSERT_XX()` macros. Therefore we only do it where it's most needed
  50. (otherwise we make the implementation of googletest harder to maintain and more
  51. error-prone than necessary).
  52. The `EXPECT_EQ()` macro takes the *expected* value as its first argument and the
  53. *actual* value as the second. It's reasonable that someone wants to write
  54. `EXPECT_EQ(NULL, some_expression)`, and this indeed was requested several times.
  55. Therefore we implemented it.
  56. The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the assertion
  57. fails, you already know that `ptr` must be `NULL`, so it doesn't add any
  58. information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)`
  59. works just as well.
  60. If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll have to
  61. support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, we don't have a
  62. convention on the order of the two arguments for `EXPECT_NE`. This means using
  63. the template meta programming tricks twice in the implementation, making it even
  64. harder to understand and maintain. We believe the benefit doesn't justify the
  65. cost.
  66. Finally, with the growth of the gMock matcher library, we are encouraging people
  67. to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One
  68. significant advantage of the matcher approach is that matchers can be easily
  69. combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be
  70. easily combined. Therefore we want to invest more in the matchers than in the
  71. `EXPECT_XX()` macros.
  72. ## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests?
  73. For testing various implementations of the same interface, either typed tests or
  74. value-parameterized tests can get it done. It's really up to you the user to
  75. decide which is more convenient for you, depending on your particular case. Some
  76. rough guidelines:
  77. * Typed tests can be easier to write if instances of the different
  78. implementations can be created the same way, modulo the type. For example,
  79. if all these implementations have a public default constructor (such that
  80. you can write `new TypeParam`), or if their factory functions have the same
  81. form (e.g. `CreateInstance<TypeParam>()`).
  82. * Value-parameterized tests can be easier to write if you need different code
  83. patterns to create different implementations' instances, e.g. `new Foo` vs
  84. `new Bar(5)`. To accommodate for the differences, you can write factory
  85. function wrappers and pass these function pointers to the tests as their
  86. parameters.
  87. * When a typed test fails, the default output includes the name of the type,
  88. which can help you quickly identify which implementation is wrong.
  89. Value-parameterized tests only show the number of the failed iteration by
  90. default. You will need to define a function that returns the iteration name
  91. and pass it as the third parameter to INSTANTIATE_TEST_SUITE_P to have more
  92. useful output.
  93. * When using typed tests, you need to make sure you are testing against the
  94. interface type, not the concrete types (in other words, you want to make
  95. sure `implicit_cast<MyInterface*>(my_concrete_impl)` works, not just that
  96. `my_concrete_impl` works). It's less likely to make mistakes in this area
  97. when using value-parameterized tests.
  98. I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give
  99. both approaches a try. Practice is a much better way to grasp the subtle
  100. differences between the two tools. Once you have some concrete experience, you
  101. can much more easily decide which one to use the next time.
  102. ## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!
  103. **Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated*
  104. now. Please use `EqualsProto`, etc instead.
  105. `ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and
  106. are now less tolerant of invalid protocol buffer definitions. In particular, if
  107. you have a `foo.proto` that doesn't fully qualify the type of a protocol message
  108. it references (e.g. `message<Bar>` where it should be `message<blah.Bar>`), you
  109. will now get run-time errors like:
  110. ```
  111. ... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto":
  112. ... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined.
  113. ```
  114. If you see this, your `.proto` file is broken and needs to be fixed by making
  115. the types fully qualified. The new definition of `ProtocolMessageEquals` and
  116. `ProtocolMessageEquiv` just happen to reveal your bug.
  117. ## My death test modifies some state, but the change seems lost after the death test finishes. Why?
  118. Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
  119. expected crash won't kill the test program (i.e. the parent process). As a
  120. result, any in-memory side effects they incur are observable in their respective
  121. sub-processes, but not in the parent process. You can think of them as running
  122. in a parallel universe, more or less.
  123. In particular, if you use mocking and the death test statement invokes some mock
  124. methods, the parent process will think the calls have never occurred. Therefore,
  125. you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH`
  126. macro.
  127. ## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug?
  128. Actually, the bug is in `htonl()`.
  129. According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to
  130. use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as
  131. a *macro*, which breaks this usage.
  132. Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not*
  133. standard C++. That hacky implementation has some ad hoc limitations. In
  134. particular, it prevents you from writing `Foo<sizeof(htonl(x))>()`, where `Foo`
  135. is a template that has an integral argument.
  136. The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a
  137. template argument, and thus doesn't compile in opt mode when `a` contains a call
  138. to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as
  139. the solution must work with different compilers on various platforms.
  140. `htonl()` has some other problems as described in `//util/endian/endian.h`,
  141. which defines `ghtonl()` to replace it. `ghtonl()` does the same thing `htonl()`
  142. does, only without its problems. We suggest you to use `ghtonl()` instead of
  143. `htonl()`, both in your tests and production code.
  144. `//util/endian/endian.h` also defines `ghtons()`, which solves similar problems
  145. in `htons()`.
  146. Don't forget to add `//util/endian` to the list of dependencies in the `BUILD`
  147. file wherever `ghtonl()` and `ghtons()` are used. The library consists of a
  148. single header file and will not bloat your binary.
  149. ## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong?
  150. If your class has a static data member:
  151. ```c++
  152. // foo.h
  153. class Foo {
  154. ...
  155. static const int kBar = 100;
  156. };
  157. ```
  158. You also need to define it *outside* of the class body in `foo.cc`:
  159. ```c++
  160. const int Foo::kBar; // No initializer here.
  161. ```
  162. Otherwise your code is **invalid C++**, and may break in unexpected ways. In
  163. particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will
  164. generate an "undefined reference" linker error. The fact that "it used to work"
  165. doesn't mean it's valid. It just means that you were lucky. :-)
  166. ## Can I derive a test fixture from another?
  167. Yes.
  168. Each test fixture has a corresponding and same named test suite. This means only
  169. one test suite can use a particular fixture. Sometimes, however, multiple test
  170. cases may want to use the same or slightly different fixtures. For example, you
  171. may want to make sure that all of a GUI library's test suites don't leak
  172. important system resources like fonts and brushes.
  173. In googletest, you share a fixture among test suites by putting the shared logic
  174. in a base test fixture, then deriving from that base a separate fixture for each
  175. test suite that wants to use this common logic. You then use `TEST_F()` to write
  176. tests using each derived fixture.
  177. Typically, your code looks like this:
  178. ```c++
  179. // Defines a base test fixture.
  180. class BaseTest : public ::testing::Test {
  181. protected:
  182. ...
  183. };
  184. // Derives a fixture FooTest from BaseTest.
  185. class FooTest : public BaseTest {
  186. protected:
  187. void SetUp() override {
  188. BaseTest::SetUp(); // Sets up the base fixture first.
  189. ... additional set-up work ...
  190. }
  191. void TearDown() override {
  192. ... clean-up work for FooTest ...
  193. BaseTest::TearDown(); // Remember to tear down the base fixture
  194. // after cleaning up FooTest!
  195. }
  196. ... functions and variables for FooTest ...
  197. };
  198. // Tests that use the fixture FooTest.
  199. TEST_F(FooTest, Bar) { ... }
  200. TEST_F(FooTest, Baz) { ... }
  201. ... additional fixtures derived from BaseTest ...
  202. ```
  203. If necessary, you can continue to derive test fixtures from a derived fixture.
  204. googletest has no limit on how deep the hierarchy can be.
  205. For a complete example using derived test fixtures, see
  206. [sample5_unittest.cc](../samples/sample5_unittest.cc).
  207. ## My compiler complains "void value not ignored as it ought to be." What does this mean?
  208. You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
  209. `ASSERT_*()` can only be used in `void` functions, due to exceptions being
  210. disabled by our build system. Please see more details
  211. [here](advanced.md#assertion-placement).
  212. ## My death test hangs (or seg-faults). How do I fix it?
  213. In googletest, death tests are run in a child process and the way they work is
  214. delicate. To write death tests you really need to understand how they work.
  215. Please make sure you have read [this](advanced.md#how-it-works).
  216. In particular, death tests don't like having multiple threads in the parent
  217. process. So the first thing you can try is to eliminate creating threads outside
  218. of `EXPECT_DEATH()`. For example, you may want to use mocks or fake objects
  219. instead of real ones in your tests.
  220. Sometimes this is impossible as some library you must use may be creating
  221. threads before `main()` is even reached. In this case, you can try to minimize
  222. the chance of conflicts by either moving as many activities as possible inside
  223. `EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
  224. leaving as few things as possible in it. Also, you can try to set the death test
  225. style to `"threadsafe"`, which is safer but slower, and see if it helps.
  226. If you go with thread-safe death tests, remember that they rerun the test
  227. program from the beginning in the child process. Therefore make sure your
  228. program can run side-by-side with itself and is deterministic.
  229. In the end, this boils down to good concurrent programming. You have to make
  230. sure that there is no race conditions or dead locks in your program. No silver
  231. bullet - sorry!
  232. ## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}
  233. The first thing to remember is that googletest does **not** reuse the same test
  234. fixture object across multiple tests. For each `TEST_F`, googletest will create
  235. a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
  236. call `TearDown()`, and then delete the test fixture object.
  237. When you need to write per-test set-up and tear-down logic, you have the choice
  238. between using the test fixture constructor/destructor or `SetUp()/TearDown()`.
  239. The former is usually preferred, as it has the following benefits:
  240. * By initializing a member variable in the constructor, we have the option to
  241. make it `const`, which helps prevent accidental changes to its value and
  242. makes the tests more obviously correct.
  243. * In case we need to subclass the test fixture class, the subclass'
  244. constructor is guaranteed to call the base class' constructor *first*, and
  245. the subclass' destructor is guaranteed to call the base class' destructor
  246. *afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of
  247. forgetting to call the base class' `SetUp()/TearDown()` or call them at the
  248. wrong time.
  249. You may still want to use `SetUp()/TearDown()` in the following cases:
  250. * C++ does not allow virtual function calls in constructors and destructors.
  251. You can call a method declared as virtual, but it will not use dynamic
  252. dispatch, it will use the definition from the class the constructor of which
  253. is currently executing. This is because calling a virtual method before the
  254. derived class constructor has a chance to run is very dangerous - the
  255. virtual method might operate on uninitialized data. Therefore, if you need
  256. to call a method that will be overridden in a derived class, you have to use
  257. `SetUp()/TearDown()`.
  258. * In the body of a constructor (or destructor), it's not possible to use the
  259. `ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal
  260. test failure that should prevent the test from running, it's necessary to
  261. use `abort` <!-- GOOGLETEST_CM0015 DO NOT DELETE --> and abort the whole test executable,
  262. or to use `SetUp()` instead of a constructor.
  263. * If the tear-down operation could throw an exception, you must use
  264. `TearDown()` as opposed to the destructor, as throwing in a destructor leads
  265. to undefined behavior and usually will kill your program right away. Note
  266. that many standard libraries (like STL) may throw when exceptions are
  267. enabled in the compiler. Therefore you should prefer `TearDown()` if you
  268. want to write portable tests that work with or without exceptions.
  269. * The googletest team is considering making the assertion macros throw on
  270. platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux
  271. client-side), which will eliminate the need for the user to propagate
  272. failures from a subroutine to its caller. Therefore, you shouldn't use
  273. googletest assertions in a destructor if your code could run on such a
  274. platform.
  275. ## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it?
  276. If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
  277. overloaded or a template, the compiler will have trouble figuring out which
  278. overloaded version it should use. `ASSERT_PRED_FORMAT*` and
  279. `EXPECT_PRED_FORMAT*` don't have this problem.
  280. If you see this error, you might want to switch to
  281. `(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
  282. message. If, however, that is not an option, you can resolve the problem by
  283. explicitly telling the compiler which version to pick.
  284. For example, suppose you have
  285. ```c++
  286. bool IsPositive(int n) {
  287. return n > 0;
  288. }
  289. bool IsPositive(double x) {
  290. return x > 0;
  291. }
  292. ```
  293. you will get a compiler error if you write
  294. ```c++
  295. EXPECT_PRED1(IsPositive, 5);
  296. ```
  297. However, this will work:
  298. ```c++
  299. EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
  300. ```
  301. (The stuff inside the angled brackets for the `static_cast` operator is the type
  302. of the function pointer for the `int`-version of `IsPositive()`.)
  303. As another example, when you have a template function
  304. ```c++
  305. template <typename T>
  306. bool IsNegative(T x) {
  307. return x < 0;
  308. }
  309. ```
  310. you can use it in a predicate assertion like this:
  311. ```c++
  312. ASSERT_PRED1(IsNegative<int>, -5);
  313. ```
  314. Things are more interesting if your template has more than one parameters. The
  315. following won't compile:
  316. ```c++
  317. ASSERT_PRED2(GreaterThan<int, int>, 5, 0);
  318. ```
  319. as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which
  320. is one more than expected. The workaround is to wrap the predicate function in
  321. parentheses:
  322. ```c++
  323. ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
  324. ```
  325. ## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why?
  326. Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
  327. instead of
  328. ```c++
  329. return RUN_ALL_TESTS();
  330. ```
  331. they write
  332. ```c++
  333. RUN_ALL_TESTS();
  334. ```
  335. This is **wrong and dangerous**. The testing services needs to see the return
  336. value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your
  337. `main()` function ignores it, your test will be considered successful even if it
  338. has a googletest assertion failure. Very bad.
  339. We have decided to fix this (thanks to Michael Chastain for the idea). Now, your
  340. code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with
  341. `gcc`. If you do so, you'll get a compiler error.
  342. If you see the compiler complaining about you ignoring the return value of
  343. `RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the
  344. return value of `main()`.
  345. But how could we introduce a change that breaks existing tests? Well, in this
  346. case, the code was already broken in the first place, so we didn't break it. :-)
  347. ## My compiler complains that a constructor (or destructor) cannot return a value. What's going on?
  348. Due to a peculiarity of C++, in order to support the syntax for streaming
  349. messages to an `ASSERT_*`, e.g.
  350. ```c++
  351. ASSERT_EQ(1, Foo()) << "blah blah" << foo;
  352. ```
  353. we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
  354. `ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
  355. content of your constructor/destructor to a private void member function, or
  356. switch to `EXPECT_*()` if that works. This
  357. [section](advanced.md#assertion-placement) in the user's guide explains it.
  358. ## My SetUp() function is not called. Why?
  359. C++ is case-sensitive. Did you spell it as `Setup()`?
  360. Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and
  361. wonder why it's never called.
  362. ## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious.
  363. You don't have to. Instead of
  364. ```c++
  365. class FooTest : public BaseTest {};
  366. TEST_F(FooTest, Abc) { ... }
  367. TEST_F(FooTest, Def) { ... }
  368. class BarTest : public BaseTest {};
  369. TEST_F(BarTest, Abc) { ... }
  370. TEST_F(BarTest, Def) { ... }
  371. ```
  372. you can simply `typedef` the test fixtures:
  373. ```c++
  374. typedef BaseTest FooTest;
  375. TEST_F(FooTest, Abc) { ... }
  376. TEST_F(FooTest, Def) { ... }
  377. typedef BaseTest BarTest;
  378. TEST_F(BarTest, Abc) { ... }
  379. TEST_F(BarTest, Def) { ... }
  380. ```
  381. ## googletest output is buried in a whole bunch of LOG messages. What do I do?
  382. The googletest output is meant to be a concise and human-friendly report. If
  383. your test generates textual output itself, it will mix with the googletest
  384. output, making it hard to read. However, there is an easy solution to this
  385. problem.
  386. Since `LOG` messages go to stderr, we decided to let googletest output go to
  387. stdout. This way, you can easily separate the two using redirection. For
  388. example:
  389. ```shell
  390. $ ./my_test > gtest_output.txt
  391. ```
  392. ## Why should I prefer test fixtures over global variables?
  393. There are several good reasons:
  394. 1. It's likely your test needs to change the states of its global variables.
  395. This makes it difficult to keep side effects from escaping one test and
  396. contaminating others, making debugging difficult. By using fixtures, each
  397. test has a fresh set of variables that's different (but with the same
  398. names). Thus, tests are kept independent of each other.
  399. 2. Global variables pollute the global namespace.
  400. 3. Test fixtures can be reused via subclassing, which cannot be done easily
  401. with global variables. This is useful if many test suites have something in
  402. common.
  403. ## What can the statement argument in ASSERT_DEATH() be?
  404. `ASSERT_DEATH(*statement*, *regex*)` (or any death assertion macro) can be used
  405. wherever `*statement*` is valid. So basically `*statement*` can be any C++
  406. statement that makes sense in the current context. In particular, it can
  407. reference global and/or local variables, and can be:
  408. * a simple function call (often the case),
  409. * a complex expression, or
  410. * a compound statement.
  411. Some examples are shown here:
  412. ```c++
  413. // A death test can be a simple function call.
  414. TEST(MyDeathTest, FunctionCall) {
  415. ASSERT_DEATH(Xyz(5), "Xyz failed");
  416. }
  417. // Or a complex expression that references variables and functions.
  418. TEST(MyDeathTest, ComplexExpression) {
  419. const bool c = Condition();
  420. ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
  421. "(Func1|Method) failed");
  422. }
  423. // Death assertions can be used any where in a function. In
  424. // particular, they can be inside a loop.
  425. TEST(MyDeathTest, InsideLoop) {
  426. // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
  427. for (int i = 0; i < 5; i++) {
  428. EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
  429. ::testing::Message() << "where i is " << i);
  430. }
  431. }
  432. // A death assertion can contain a compound statement.
  433. TEST(MyDeathTest, CompoundStatement) {
  434. // Verifies that at lease one of Bar(0), Bar(1), ..., and
  435. // Bar(4) dies.
  436. ASSERT_DEATH({
  437. for (int i = 0; i < 5; i++) {
  438. Bar(i);
  439. }
  440. },
  441. "Bar has \\d+ errors");
  442. }
  443. ```
  444. gtest-death-test_test.cc contains more examples if you are interested.
  445. ## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why?
  446. Googletest needs to be able to create objects of your test fixture class, so it
  447. must have a default constructor. Normally the compiler will define one for you.
  448. However, there are cases where you have to define your own:
  449. * If you explicitly declare a non-default constructor for class `FooTest`
  450. (`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a
  451. default constructor, even if it would be empty.
  452. * If `FooTest` has a const non-static data member, then you have to define the
  453. default constructor *and* initialize the const member in the initializer
  454. list of the constructor. (Early versions of `gcc` doesn't force you to
  455. initialize the const member. It's a bug that has been fixed in `gcc 4`.)
  456. ## Why does ASSERT_DEATH complain about previous threads that were already joined?
  457. With the Linux pthread library, there is no turning back once you cross the line
  458. from single thread to multiple threads. The first time you create a thread, a
  459. manager thread is created in addition, so you get 3, not 2, threads. Later when
  460. the thread you create joins the main thread, the thread count decrements by 1,
  461. but the manager thread will never be killed, so you still have 2 threads, which
  462. means you cannot safely run a death test.
  463. The new NPTL thread library doesn't suffer from this problem, as it doesn't
  464. create a manager thread. However, if you don't control which machine your test
  465. runs on, you shouldn't depend on this.
  466. ## Why does googletest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
  467. googletest does not interleave tests from different test suites. That is, it
  468. runs all tests in one test suite first, and then runs all tests in the next test
  469. suite, and so on. googletest does this because it needs to set up a test suite
  470. before the first test in it is run, and tear it down afterwords. Splitting up
  471. the test case would require multiple set-up and tear-down processes, which is
  472. inefficient and makes the semantics unclean.
  473. If we were to determine the order of tests based on test name instead of test
  474. case name, then we would have a problem with the following situation:
  475. ```c++
  476. TEST_F(FooTest, AbcDeathTest) { ... }
  477. TEST_F(FooTest, Uvw) { ... }
  478. TEST_F(BarTest, DefDeathTest) { ... }
  479. TEST_F(BarTest, Xyz) { ... }
  480. ```
  481. Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
  482. interleave tests from different test suites, we need to run all tests in the
  483. `FooTest` case before running any test in the `BarTest` case. This contradicts
  484. with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
  485. ## But I don't like calling my entire test suite \*DeathTest when it contains both death tests and non-death tests. What do I do?
  486. You don't have to, but if you like, you may split up the test suite into
  487. `FooTest` and `FooDeathTest`, where the names make it clear that they are
  488. related:
  489. ```c++
  490. class FooTest : public ::testing::Test { ... };
  491. TEST_F(FooTest, Abc) { ... }
  492. TEST_F(FooTest, Def) { ... }
  493. using FooDeathTest = FooTest;
  494. TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
  495. TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
  496. ```
  497. ## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
  498. Printing the LOG messages generated by the statement inside `EXPECT_DEATH()`
  499. makes it harder to search for real problems in the parent's log. Therefore,
  500. googletest only prints them when the death test has failed.
  501. If you really need to see such LOG messages, a workaround is to temporarily
  502. break the death test (e.g. by changing the regex pattern it is expected to
  503. match). Admittedly, this is a hack. We'll consider a more permanent solution
  504. after the fork-and-exec-style death tests are implemented.
  505. ## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives?
  506. If you use a user-defined type `FooType` in an assertion, you must make sure
  507. there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
  508. defined such that we can print a value of `FooType`.
  509. In addition, if `FooType` is declared in a name space, the `<<` operator also
  510. needs to be defined in the *same* name space. See https://abseil.io/tips/49 for details.
  511. ## How do I suppress the memory leak messages on Windows?
  512. Since the statically initialized googletest singleton requires allocations on
  513. the heap, the Visual C++ memory leak detector will report memory leaks at the
  514. end of the program run. The easiest way to avoid this is to use the
  515. `_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
  516. statically initialized heap objects. See MSDN for more details and additional
  517. heap check/debug routines.
  518. ## How can my code detect if it is running in a test?
  519. If you write code that sniffs whether it's running in a test and does different
  520. things accordingly, you are leaking test-only logic into production code and
  521. there is no easy way to ensure that the test-only code paths aren't run by
  522. mistake in production. Such cleverness also leads to
  523. [Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly
  524. advise against the practice, and googletest doesn't provide a way to do it.
  525. In general, the recommended way to cause the code to behave differently under
  526. test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject
  527. different functionality from the test and from the production code. Since your
  528. production code doesn't link in the for-test logic at all (the
  529. [`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure
  530. that), there is no danger in accidentally running it.
  531. However, if you *really*, *really*, *really* have no choice, and if you follow
  532. the rule of ending your test program names with `_test`, you can use the
  533. *horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know
  534. whether the code is under test.
  535. ## How do I temporarily disable a test?
  536. If you have a broken test that you cannot fix right away, you can add the
  537. DISABLED_ prefix to its name. This will exclude it from execution. This is
  538. better than commenting out the code or using #if 0, as disabled tests are still
  539. compiled (and thus won't rot).
  540. To include disabled tests in test execution, just invoke the test program with
  541. the --gtest_also_run_disabled_tests flag.
  542. ## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces?
  543. Yes.
  544. The rule is **all test methods in the same test suite must use the same fixture
  545. class.** This means that the following is **allowed** because both tests use the
  546. same fixture class (`::testing::Test`).
  547. ```c++
  548. namespace foo {
  549. TEST(CoolTest, DoSomething) {
  550. SUCCEED();
  551. }
  552. } // namespace foo
  553. namespace bar {
  554. TEST(CoolTest, DoSomething) {
  555. SUCCEED();
  556. }
  557. } // namespace bar
  558. ```
  559. However, the following code is **not allowed** and will produce a runtime error
  560. from googletest because the test methods are using different test fixture
  561. classes with the same test suite name.
  562. ```c++
  563. namespace foo {
  564. class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest
  565. TEST_F(CoolTest, DoSomething) {
  566. SUCCEED();
  567. }
  568. } // namespace foo
  569. namespace bar {
  570. class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest
  571. TEST_F(CoolTest, DoSomething) {
  572. SUCCEED();
  573. }
  574. } // namespace bar
  575. ```