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