LevelDB project 1 10225501460 林子骥 10211900416 郭夏辉
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.

756 lines
31 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.
  220. Please make sure you have read [this](advanced.md#how-it-works).
  221. In particular, death tests don't like having multiple threads in the parent
  222. process. So the first thing you can try is to eliminate creating threads outside
  223. of `EXPECT_DEATH()`. For example, you may want to use mocks or fake objects
  224. instead of real ones in your tests.
  225. Sometimes this is impossible as some library you must use may be creating
  226. threads before `main()` is even reached. In this case, you can try to minimize
  227. the chance of conflicts by either moving as many activities as possible inside
  228. `EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
  229. leaving as few things as possible in it. Also, you can try to set the death test
  230. style to `"threadsafe"`, which is safer but slower, and see if it helps.
  231. If you go with thread-safe death tests, remember that they rerun the test
  232. program from the beginning in the child process. Therefore make sure your
  233. program can run side-by-side with itself and is deterministic.
  234. In the end, this boils down to good concurrent programming. You have to make
  235. sure that there are no race conditions or deadlocks in your program. No silver
  236. bullet - sorry!
  237. ## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}
  238. The first thing to remember is that googletest does **not** reuse the same test
  239. fixture object across multiple tests. For each `TEST_F`, googletest will create
  240. a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
  241. call `TearDown()`, and then delete the test fixture object.
  242. When you need to write per-test set-up and tear-down logic, you have the choice
  243. between using the test fixture constructor/destructor or `SetUp()/TearDown()`.
  244. The former is usually preferred, as it has the following benefits:
  245. * By initializing a member variable in the constructor, we have the option to
  246. make it `const`, which helps prevent accidental changes to its value and
  247. makes the tests more obviously correct.
  248. * In case we need to subclass the test fixture class, the subclass'
  249. constructor is guaranteed to call the base class' constructor *first*, and
  250. the subclass' destructor is guaranteed to call the base class' destructor
  251. *afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of
  252. forgetting to call the base class' `SetUp()/TearDown()` or call them at the
  253. wrong time.
  254. You may still want to use `SetUp()/TearDown()` in the following cases:
  255. * C++ does not allow virtual function calls in constructors and destructors.
  256. You can call a method declared as virtual, but it will not use dynamic
  257. dispatch, it will use the definition from the class the constructor of which
  258. is currently executing. This is because calling a virtual method before the
  259. derived class constructor has a chance to run is very dangerous - the
  260. virtual method might operate on uninitialized data. Therefore, if you need
  261. to call a method that will be overridden in a derived class, you have to use
  262. `SetUp()/TearDown()`.
  263. * In the body of a constructor (or destructor), it's not possible to use the
  264. `ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal
  265. test failure that should prevent the test from running, it's necessary to
  266. use `abort` and abort the whole test
  267. executable, or to use `SetUp()` instead of a constructor.
  268. * If the tear-down operation could throw an exception, you must use
  269. `TearDown()` as opposed to the destructor, as throwing in a destructor leads
  270. to undefined behavior and usually will kill your program right away. Note
  271. that many standard libraries (like STL) may throw when exceptions are
  272. enabled in the compiler. Therefore you should prefer `TearDown()` if you
  273. want to write portable tests that work with or without exceptions.
  274. * The googletest team is considering making the assertion macros throw on
  275. platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux
  276. client-side), which will eliminate the need for the user to propagate
  277. failures from a subroutine to its caller. Therefore, you shouldn't use
  278. googletest assertions in a destructor if your code could run on such a
  279. platform.
  280. ## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it?
  281. If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
  282. overloaded or a template, the compiler will have trouble figuring out which
  283. overloaded version it should use. `ASSERT_PRED_FORMAT*` and
  284. `EXPECT_PRED_FORMAT*` don't have this problem.
  285. If you see this error, you might want to switch to
  286. `(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
  287. message. If, however, that is not an option, you can resolve the problem by
  288. explicitly telling the compiler which version to pick.
  289. For example, suppose you have
  290. ```c++
  291. bool IsPositive(int n) {
  292. return n > 0;
  293. }
  294. bool IsPositive(double x) {
  295. return x > 0;
  296. }
  297. ```
  298. you will get a compiler error if you write
  299. ```c++
  300. EXPECT_PRED1(IsPositive, 5);
  301. ```
  302. However, this will work:
  303. ```c++
  304. EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
  305. ```
  306. (The stuff inside the angled brackets for the `static_cast` operator is the type
  307. of the function pointer for the `int`-version of `IsPositive()`.)
  308. As another example, when you have a template function
  309. ```c++
  310. template <typename T>
  311. bool IsNegative(T x) {
  312. return x < 0;
  313. }
  314. ```
  315. you can use it in a predicate assertion like this:
  316. ```c++
  317. ASSERT_PRED1(IsNegative<int>, -5);
  318. ```
  319. Things are more interesting if your template has more than one parameter. The
  320. following won't compile:
  321. ```c++
  322. ASSERT_PRED2(GreaterThan<int, int>, 5, 0);
  323. ```
  324. as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which
  325. is one more than expected. The workaround is to wrap the predicate function in
  326. parentheses:
  327. ```c++
  328. ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
  329. ```
  330. ## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why?
  331. Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
  332. instead of
  333. ```c++
  334. return RUN_ALL_TESTS();
  335. ```
  336. they write
  337. ```c++
  338. RUN_ALL_TESTS();
  339. ```
  340. This is **wrong and dangerous**. The testing services needs to see the return
  341. value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your
  342. `main()` function ignores it, your test will be considered successful even if it
  343. has a googletest assertion failure. Very bad.
  344. We have decided to fix this (thanks to Michael Chastain for the idea). Now, your
  345. code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with
  346. `gcc`. If you do so, you'll get a compiler error.
  347. If you see the compiler complaining about you ignoring the return value of
  348. `RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the
  349. return value of `main()`.
  350. But how could we introduce a change that breaks existing tests? Well, in this
  351. case, the code was already broken in the first place, so we didn't break it. :-)
  352. ## My compiler complains that a constructor (or destructor) cannot return a value. What's going on?
  353. Due to a peculiarity of C++, in order to support the syntax for streaming
  354. messages to an `ASSERT_*`, e.g.
  355. ```c++
  356. ASSERT_EQ(1, Foo()) << "blah blah" << foo;
  357. ```
  358. we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
  359. `ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
  360. content of your constructor/destructor to a private void member function, or
  361. switch to `EXPECT_*()` if that works. This
  362. [section](advanced.md#assertion-placement) in the user's guide explains it.
  363. ## My SetUp() function is not called. Why?
  364. C++ is case-sensitive. Did you spell it as `Setup()`?
  365. Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and
  366. wonder why it's never called.
  367. ## 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.
  368. You don't have to. Instead of
  369. ```c++
  370. class FooTest : public BaseTest {};
  371. TEST_F(FooTest, Abc) { ... }
  372. TEST_F(FooTest, Def) { ... }
  373. class BarTest : public BaseTest {};
  374. TEST_F(BarTest, Abc) { ... }
  375. TEST_F(BarTest, Def) { ... }
  376. ```
  377. you can simply `typedef` the test fixtures:
  378. ```c++
  379. typedef BaseTest FooTest;
  380. TEST_F(FooTest, Abc) { ... }
  381. TEST_F(FooTest, Def) { ... }
  382. typedef BaseTest BarTest;
  383. TEST_F(BarTest, Abc) { ... }
  384. TEST_F(BarTest, Def) { ... }
  385. ```
  386. ## googletest output is buried in a whole bunch of LOG messages. What do I do?
  387. The googletest output is meant to be a concise and human-friendly report. If
  388. your test generates textual output itself, it will mix with the googletest
  389. output, making it hard to read. However, there is an easy solution to this
  390. problem.
  391. Since `LOG` messages go to stderr, we decided to let googletest output go to
  392. stdout. This way, you can easily separate the two using redirection. For
  393. example:
  394. ```shell
  395. $ ./my_test > gtest_output.txt
  396. ```
  397. ## Why should I prefer test fixtures over global variables?
  398. There are several good reasons:
  399. 1. It's likely your test needs to change the states of its global variables.
  400. This makes it difficult to keep side effects from escaping one test and
  401. contaminating others, making debugging difficult. By using fixtures, each
  402. test has a fresh set of variables that's different (but with the same
  403. names). Thus, tests are kept independent of each other.
  404. 2. Global variables pollute the global namespace.
  405. 3. Test fixtures can be reused via subclassing, which cannot be done easily
  406. with global variables. This is useful if many test suites have something in
  407. common.
  408. ## What can the statement argument in ASSERT_DEATH() be?
  409. `ASSERT_DEATH(statement, matcher)` (or any death assertion macro) can be used
  410. wherever *`statement`* is valid. So basically *`statement`* can be any C++
  411. statement that makes sense in the current context. In particular, it can
  412. reference global and/or local variables, and can be:
  413. * a simple function call (often the case),
  414. * a complex expression, or
  415. * a compound statement.
  416. Some examples are shown here:
  417. ```c++
  418. // A death test can be a simple function call.
  419. TEST(MyDeathTest, FunctionCall) {
  420. ASSERT_DEATH(Xyz(5), "Xyz failed");
  421. }
  422. // Or a complex expression that references variables and functions.
  423. TEST(MyDeathTest, ComplexExpression) {
  424. const bool c = Condition();
  425. ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
  426. "(Func1|Method) failed");
  427. }
  428. // Death assertions can be used anywhere in a function. In
  429. // particular, they can be inside a loop.
  430. TEST(MyDeathTest, InsideLoop) {
  431. // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
  432. for (int i = 0; i < 5; i++) {
  433. EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
  434. ::testing::Message() << "where i is " << i);
  435. }
  436. }
  437. // A death assertion can contain a compound statement.
  438. TEST(MyDeathTest, CompoundStatement) {
  439. // Verifies that at lease one of Bar(0), Bar(1), ..., and
  440. // Bar(4) dies.
  441. ASSERT_DEATH({
  442. for (int i = 0; i < 5; i++) {
  443. Bar(i);
  444. }
  445. },
  446. "Bar has \\d+ errors");
  447. }
  448. ```
  449. ## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why?
  450. Googletest needs to be able to create objects of your test fixture class, so it
  451. must have a default constructor. Normally the compiler will define one for you.
  452. However, there are cases where you have to define your own:
  453. * If you explicitly declare a non-default constructor for class `FooTest`
  454. (`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a
  455. default constructor, even if it would be empty.
  456. * If `FooTest` has a const non-static data member, then you have to define the
  457. default constructor *and* initialize the const member in the initializer
  458. list of the constructor. (Early versions of `gcc` doesn't force you to
  459. initialize the const member. It's a bug that has been fixed in `gcc 4`.)
  460. ## Why does ASSERT_DEATH complain about previous threads that were already joined?
  461. With the Linux pthread library, there is no turning back once you cross the line
  462. from a single thread to multiple threads. The first time you create a thread, a
  463. manager thread is created in addition, so you get 3, not 2, threads. Later when
  464. the thread you create joins the main thread, the thread count decrements by 1,
  465. but the manager thread will never be killed, so you still have 2 threads, which
  466. means you cannot safely run a death test.
  467. The new NPTL thread library doesn't suffer from this problem, as it doesn't
  468. create a manager thread. However, if you don't control which machine your test
  469. runs on, you shouldn't depend on this.
  470. ## Why does googletest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
  471. googletest does not interleave tests from different test suites. That is, it
  472. runs all tests in one test suite first, and then runs all tests in the next test
  473. suite, and so on. googletest does this because it needs to set up a test suite
  474. before the first test in it is run, and tear it down afterwards. Splitting up
  475. the test case would require multiple set-up and tear-down processes, which is
  476. inefficient and makes the semantics unclean.
  477. If we were to determine the order of tests based on test name instead of test
  478. case name, then we would have a problem with the following situation:
  479. ```c++
  480. TEST_F(FooTest, AbcDeathTest) { ... }
  481. TEST_F(FooTest, Uvw) { ... }
  482. TEST_F(BarTest, DefDeathTest) { ... }
  483. TEST_F(BarTest, Xyz) { ... }
  484. ```
  485. Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
  486. interleave tests from different test suites, we need to run all tests in the
  487. `FooTest` case before running any test in the `BarTest` case. This contradicts
  488. with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
  489. ## 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?
  490. You don't have to, but if you like, you may split up the test suite into
  491. `FooTest` and `FooDeathTest`, where the names make it clear that they are
  492. related:
  493. ```c++
  494. class FooTest : public ::testing::Test { ... };
  495. TEST_F(FooTest, Abc) { ... }
  496. TEST_F(FooTest, Def) { ... }
  497. using FooDeathTest = FooTest;
  498. TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
  499. TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
  500. ```
  501. ## 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?
  502. Printing the LOG messages generated by the statement inside `EXPECT_DEATH()`
  503. makes it harder to search for real problems in the parent's log. Therefore,
  504. googletest only prints them when the death test has failed.
  505. If you really need to see such LOG messages, a workaround is to temporarily
  506. break the death test (e.g. by changing the regex pattern it is expected to
  507. match). Admittedly, this is a hack. We'll consider a more permanent solution
  508. after the fork-and-exec-style death tests are implemented.
  509. ## The compiler complains about `no match for 'operator<<'` when I use an assertion. What gives?
  510. If you use a user-defined type `FooType` in an assertion, you must make sure
  511. there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
  512. defined such that we can print a value of `FooType`.
  513. In addition, if `FooType` is declared in a name space, the `<<` operator also
  514. needs to be defined in the *same* name space. See
  515. [Tip of the Week #49](http://abseil.io/tips/49) for details.
  516. ## How do I suppress the memory leak messages on Windows?
  517. Since the statically initialized googletest singleton requires allocations on
  518. the heap, the Visual C++ memory leak detector will report memory leaks at the
  519. end of the program run. The easiest way to avoid this is to use the
  520. `_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
  521. statically initialized heap objects. See MSDN for more details and additional
  522. heap check/debug routines.
  523. ## How can my code detect if it is running in a test?
  524. If you write code that sniffs whether it's running in a test and does different
  525. things accordingly, you are leaking test-only logic into production code and
  526. there is no easy way to ensure that the test-only code paths aren't run by
  527. mistake in production. Such cleverness also leads to
  528. [Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly
  529. advise against the practice, and googletest doesn't provide a way to do it.
  530. In general, the recommended way to cause the code to behave differently under
  531. test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject
  532. different functionality from the test and from the production code. Since your
  533. production code doesn't link in the for-test logic at all (the
  534. [`testonly`](http://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure
  535. that), there is no danger in accidentally running it.
  536. However, if you *really*, *really*, *really* have no choice, and if you follow
  537. the rule of ending your test program names with `_test`, you can use the
  538. *horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know
  539. whether the code is under test.
  540. ## How do I temporarily disable a test?
  541. If you have a broken test that you cannot fix right away, you can add the
  542. `DISABLED_` prefix to its name. This will exclude it from execution. This is
  543. better than commenting out the code or using `#if 0`, as disabled tests are
  544. still compiled (and thus won't rot).
  545. To include disabled tests in test execution, just invoke the test program with
  546. the `--gtest_also_run_disabled_tests` flag.
  547. ## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces?
  548. Yes.
  549. The rule is **all test methods in the same test suite must use the same fixture
  550. class.** This means that the following is **allowed** because both tests use the
  551. same fixture class (`::testing::Test`).
  552. ```c++
  553. namespace foo {
  554. TEST(CoolTest, DoSomething) {
  555. SUCCEED();
  556. }
  557. } // namespace foo
  558. namespace bar {
  559. TEST(CoolTest, DoSomething) {
  560. SUCCEED();
  561. }
  562. } // namespace bar
  563. ```
  564. However, the following code is **not allowed** and will produce a runtime error
  565. from googletest because the test methods are using different test fixture
  566. classes with the same test suite name.
  567. ```c++
  568. namespace foo {
  569. class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest
  570. TEST_F(CoolTest, DoSomething) {
  571. SUCCEED();
  572. }
  573. } // namespace foo
  574. namespace bar {
  575. class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest
  576. TEST_F(CoolTest, DoSomething) {
  577. SUCCEED();
  578. }
  579. } // namespace bar
  580. ```