The source code and dockerfile for the GSW2024 AI Lab.
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

693 lines
29 KiB

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