1# Googletest FAQ
2
3
4## Why should test case names and test names not contain underscore?
5
6Underscore (`_`) is special, as C++ reserves the following to be used by the
7compiler and the standard library:
8
91.  any identifier that starts with an `_` followed by an upper-case letter, and
101.  any identifier that contains two consecutive underscores (i.e. `__`)
11    *anywhere* in its name.
12
13User code is *prohibited* from using such identifiers.
14
15Now let's look at what this means for `TEST` and `TEST_F`.
16
17Currently `TEST(TestCaseName, TestName)` generates a class named
18`TestCaseName_TestName_Test`. What happens if `TestCaseName` or `TestName`
19contains `_`?
20
211.  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.
241.  If `TestCaseName` ends with an `_` (say, `Foo_`), we get
25    `Foo__TestName_Test`, which is invalid.
261.  If `TestName` starts with an `_` (say, `_Bar`), we get
27    `TestCaseName__Bar_Test`, which is invalid.
281.  If `TestName` ends with an `_` (say, `Bar_`), we get
29    `TestCaseName_Bar__Test`, which is invalid.
30
31So clearly `TestCaseName` and `TestName` cannot start or end with `_` (Actually,
32`TestCaseName` can start with `_` -- as long as the `_` isn't followed by an
33upper-case letter. But that's getting complicated. So for simplicity we just say
34that it cannot start with `_`.).
35
36It may seem fine for `TestCaseName` and `TestName` to contain `_` in the middle.
37However, consider this:
38
39```c++
40TEST(Time, Flies_Like_An_Arrow) { ... }
41TEST(Time_Flies, Like_An_Arrow) { ... }
42```
43
44Now, the two `TEST`s will both generate the same class
45(`Time_Flies_Like_An_Arrow_Test`). That's not good.
46
47So 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
49easy to remember. It also gives googletest some wiggle room in case its
50implementation needs to change in the future.
51
52If you violate the rule, there may not be immediate consequences, but your test
53may (just may) break with a new compiler (or a new version of the compiler you
54are using) or with a new version of googletest. Therefore it's best to follow
55the 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
59First of all you can use `EXPECT_NE(nullptr, ptr)` and `ASSERT_NE(nullptr,
60ptr)`. This is the preferred syntax in the style guide because nullptr does not
61have the type problems that NULL does. Which is why NULL does not work.
62
63Due to some peculiarity of C++, it requires some non-trivial template meta
64programming tricks to support using `NULL` as an argument of the `EXPECT_XX()`
65and `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
67error-prone than necessary).
68
69The `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.
72Therefore we implemented it.
73
74The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the assertion
75fails, you already know that `ptr` must be `NULL`, so it doesn't add any
76information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)`
77works just as well.
78
79If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll have to
80support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, we don't have a
81convention on the order of the two arguments for `EXPECT_NE`. This means using
82the template meta programming tricks twice in the implementation, making it even
83harder to understand and maintain. We believe the benefit doesn't justify the
84cost.
85
86Finally, with the growth of the gMock matcher library, we are encouraging people
87to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One
88significant advantage of the matcher approach is that matchers can be easily
89combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be
90easily 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
95For testing various implementations of the same interface, either typed tests or
96value-parameterized tests can get it done. It's really up to you the user to
97decide which is more convenient for you, depending on your particular case. Some
98rough 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
122I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give
123both approaches a try. Practice is a much better way to grasp the subtle
124differences between the two tools. Once you have some concrete experience, you
125can much more easily decide which one to use the next time.
126
127## My death tests became very slow - what happened?
128
129In 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
131default. This caused many death tests to slow down. Unfortunately this change
132was necessary.
133
134Please read [Fixing Failing Death Tests](death_test_styles.md) for what you can
135do.
136
137## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!
138
139**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated*
140now. Please use `EqualsProto`, etc instead.
141
142`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and
143are now less tolerant on invalid protocol buffer definitions. In particular, if
144you have a `foo.proto` that doesn't fully qualify the type of a protocol message
145it references (e.g. `message<Bar>` where it should be `message<blah.Bar>`), you
146will 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
153If you see this, your `.proto` file is broken and needs to be fixed by making
154the 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
159Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
160expected crash won't kill the test program (i.e. the parent process). As a
161result, any in-memory side effects they incur are observable in their respective
162sub-processes, but not in the parent process. You can think of them as running
163in a parallel universe, more or less.
164
165In particular, if you use [gMock](../../googlemock) and the death test statement
166invokes some mock methods, the parent process will think the calls have never
167occurred. Therefore, you may want to move your `EXPECT_CALL` statements inside
168the `EXPECT_DEATH` macro.
169
170## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug?
171
172Actually, the bug is in `htonl()`.
173
174According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to
175use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as
176a *macro*, which breaks this usage.
177
178Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not*
179standard C++. That hacky implementation has some ad hoc limitations. In
180particular, it prevents you from writing `Foo<sizeof(htonl(x))>()`, where `Foo`
181is a template that has an integral argument.
182
183The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a
184template argument, and thus doesn't compile in opt mode when `a` contains a call
185to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as
186the solution must work with different compilers on various platforms.
187
188`htonl()` has some other problems as described in `//util/endian/endian.h`,
189which defines `ghtonl()` to replace it. `ghtonl()` does the same thing `htonl()`
190does, 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
194in `htons()`.
195
196Don't forget to add `//util/endian` to the list of dependencies in the `BUILD`
197file wherever `ghtonl()` and `ghtons()` are used. The library consists of a
198single 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
202If your class has a static data member:
203
204```c++
205// foo.h
206class Foo {
207  ...
208  static const int kBar = 100;
209};
210```
211
212You also need to define it *outside* of the class body in `foo.cc`:
213
214```c++
215const int Foo::kBar;  // No initializer here.
216```
217
218Otherwise your code is **invalid C++**, and may break in unexpected ways. In
219particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will
220generate an "undefined reference" linker error. The fact that "it used to work"
221doesn't mean it's valid. It just means that you were lucky. :-)
222
223## Can I derive a test fixture from another?
224
225Yes.
226
227Each test fixture has a corresponding and same named test case. This means only
228one test case can use a particular fixture. Sometimes, however, multiple test
229cases may want to use the same or slightly different fixtures. For example, you
230may want to make sure that all of a GUI library's test cases don't leak
231important system resources like fonts and brushes.
232
233In googletest, you share a fixture among test cases by putting the shared logic
234in a base test fixture, then deriving from that base a separate fixture for each
235test case that wants to use this common logic. You then use `TEST_F()` to write
236tests using each derived fixture.
237
238Typically, your code looks like this:
239
240```c++
241// Defines a base test fixture.
242class BaseTest : public ::testing::Test {
243 protected:
244  ...
245};
246
247// Derives a fixture FooTest from BaseTest.
248class 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.
265TEST_F(FooTest, Bar) { ... }
266TEST_F(FooTest, Baz) { ... }
267
268... additional fixtures derived from BaseTest ...
269```
270
271If necessary, you can continue to derive test fixtures from a derived fixture.
272googletest has no limit on how deep the hierarchy can be.
273
274For a complete example using derived test fixtures, see [googletest
275sample](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
279You'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
281disabled 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
286In googletest, death tests are run in a child process and the way they work is
287delicate. To write death tests you really need to understand how they work.
288Please make sure you have read [this](advanced.md#how-it-works).
289
290In particular, death tests don't like having multiple threads in the parent
291process. So the first thing you can try is to eliminate creating threads outside
292of `EXPECT_DEATH()`. For example, you may want to use [mocks](../../googlemock)
293or fake objects instead of real ones in your tests.
294
295Sometimes this is impossible as some library you must use may be creating
296threads before `main()` is even reached. In this case, you can try to minimize
297the 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
299leaving as few things as possible in it. Also, you can try to set the death test
300style to `"threadsafe"`, which is safer but slower, and see if it helps.
301
302If you go with thread-safe death tests, remember that they rerun the test
303program from the beginning in the child process. Therefore make sure your
304program can run side-by-side with itself and is deterministic.
305
306In the end, this boils down to good concurrent programming. You have to make
307sure that there is no race conditions or dead locks in your program. No silver
308bullet - sorry!
309
310## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()?
311
312The first thing to remember is that googletest does **not** reuse the same test
313fixture object across multiple tests. For each `TEST_F`, googletest will create
314a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
315call `TearDown()`, and then delete the test fixture object.
316
317When you need to write per-test set-up and tear-down logic, you have the choice
318between using the test fixture constructor/destructor or `SetUp()/TearDown()`.
319The 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
331You 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
357If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
358overloaded or a template, the compiler will have trouble figuring out which
359overloaded version it should use. `ASSERT_PRED_FORMAT*` and
360`EXPECT_PRED_FORMAT*` don't have this problem.
361
362If you see this error, you might want to switch to
363`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
364message. If, however, that is not an option, you can resolve the problem by
365explicitly telling the compiler which version to pick.
366
367For example, suppose you have
368
369```c++
370bool IsPositive(int n) {
371  return n > 0;
372}
373
374bool IsPositive(double x) {
375  return x > 0;
376}
377```
378
379you will get a compiler error if you write
380
381```c++
382EXPECT_PRED1(IsPositive, 5);
383```
384
385However, this will work:
386
387```c++
388EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
389```
390
391(The stuff inside the angled brackets for the `static_cast` operator is the type
392of the function pointer for the `int`-version of `IsPositive()`.)
393
394As another example, when you have a template function
395
396```c++
397template <typename T>
398bool IsNegative(T x) {
399  return x < 0;
400}
401```
402
403you can use it in a predicate assertion like this:
404
405```c++
406ASSERT_PRED1(IsNegative<int>, -5);
407```
408
409Things are more interesting if your template has more than one parameters. The
410following won't compile:
411
412```c++
413ASSERT_PRED2(GreaterThan<int, int>, 5, 0);
414```
415
416as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which
417is one more than expected. The workaround is to wrap the predicate function in
418parentheses:
419
420```c++
421ASSERT_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
427Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
428instead of
429
430```c++
431  return RUN_ALL_TESTS();
432```
433
434they write
435
436```c++
437  RUN_ALL_TESTS();
438```
439
440This is **wrong and dangerous**. The testing services needs to see the return
441value 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
443has a googletest assertion failure. Very bad.
444
445We have decided to fix this (thanks to Michael Chastain for the idea). Now, your
446code 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
449If 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
451return value of `main()`.
452
453But how could we introduce a change that breaks existing tests? Well, in this
454case, 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
458Due to a peculiarity of C++, in order to support the syntax for streaming
459messages to an `ASSERT_*`, e.g.
460
461```c++
462  ASSERT_EQ(1, Foo()) << "blah blah" << foo;
463```
464
465we 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
467content of your constructor/destructor to a private void member function, or
468switch 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
473C++ is case-sensitive. Did you spell it as `Setup()`?
474
475Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and
476wonder why it's never called.
477
478## How do I jump to the line of a failure in Emacs directly?
479
480googletest's failure message format is understood by Emacs and many other IDEs,
481like acme and XCode. If a googletest message is in a compilation buffer in
482Emacs, 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
487You don't have to. Instead of
488
489```c++
490class FooTest : public BaseTest {};
491
492TEST_F(FooTest, Abc) { ... }
493TEST_F(FooTest, Def) { ... }
494
495class BarTest : public BaseTest {};
496
497TEST_F(BarTest, Abc) { ... }
498TEST_F(BarTest, Def) { ... }
499```
500
501you can simply `typedef` the test fixtures:
502
503```c++
504typedef BaseTest FooTest;
505
506TEST_F(FooTest, Abc) { ... }
507TEST_F(FooTest, Def) { ... }
508
509typedef BaseTest BarTest;
510
511TEST_F(BarTest, Abc) { ... }
512TEST_F(BarTest, Def) { ... }
513```
514
515## googletest output is buried in a whole bunch of LOG messages. What do I do?
516
517The googletest output is meant to be a concise and human-friendly report. If
518your test generates textual output itself, it will mix with the googletest
519output, making it hard to read. However, there is an easy solution to this
520problem.
521
522Since `LOG` messages go to stderr, we decided to let googletest output go to
523stdout. This way, you can easily separate the two using redirection. For
524example:
525
526```shell
527$ ./my_test > gtest_output.txt
528```
529
530
531## Why should I prefer test fixtures over global variables?
532
533There are several good reasons:
534
5351.  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.
5401.  Global variables pollute the global namespace.
5411.  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
549wherever `*statement*` is valid. So basically `*statement*` can be any C++
550statement that makes sense in the current context. In particular, it can
551reference 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
557Some examples are shown here:
558
559```c++
560// A death test can be a simple function call.
561TEST(MyDeathTest, FunctionCall) {
562  ASSERT_DEATH(Xyz(5), "Xyz failed");
563}
564
565// Or a complex expression that references variables and functions.
566TEST(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.
574TEST(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.
583TEST(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
595gtest-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
599Googletest needs to be able to create objects of your test fixture class, so it
600must have a default constructor. Normally the compiler will define one for you.
601However, 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
613With the Linux pthread library, there is no turning back once you cross the line
614from single thread to multiple threads. The first time you create a thread, a
615manager thread is created in addition, so you get 3, not 2, threads. Later when
616the thread you create joins the main thread, the thread count decrements by 1,
617but the manager thread will never be killed, so you still have 2 threads, which
618means you cannot safely run a death test.
619
620The new NPTL thread library doesn't suffer from this problem, as it doesn't
621create a manager thread. However, if you don't control which machine your test
622runs 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
626googletest does not interleave tests from different test cases. That is, it runs
627all tests in one test case first, and then runs all tests in the next test case,
628and so on. googletest does this because it needs to set up a test case before
629the first test in it is run, and tear it down afterwords. Splitting up the test
630case would require multiple set-up and tear-down processes, which is inefficient
631and makes the semantics unclean.
632
633If we were to determine the order of tests based on test name instead of test
634case name, then we would have a problem with the following situation:
635
636```c++
637TEST_F(FooTest, AbcDeathTest) { ... }
638TEST_F(FooTest, Uvw) { ... }
639
640TEST_F(BarTest, DefDeathTest) { ... }
641TEST_F(BarTest, Xyz) { ... }
642```
643
644Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
645interleave 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
647with 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
651You 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
653related:
654
655```c++
656class FooTest : public ::testing::Test { ... };
657
658TEST_F(FooTest, Abc) { ... }
659TEST_F(FooTest, Def) { ... }
660
661using FooDeathTest = FooTest;
662
663TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
664TEST_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
669Printing the LOG messages generated by the statement inside `EXPECT_DEATH()`
670makes it harder to search for real problems in the parent's log. Therefore,
671googletest only prints them when the death test has failed.
672
673If you really need to see such LOG messages, a workaround is to temporarily
674break the death test (e.g. by changing the regex pattern it is expected to
675match). Admittedly, this is a hack. We'll consider a more permanent solution
676after 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
680If you use a user-defined type `FooType` in an assertion, you must make sure
681there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
682defined such that we can print a value of `FooType`.
683
684In addition, if `FooType` is declared in a name space, the `<<` operator also
685needs 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
689Since the statically initialized googletest singleton requires allocations on
690the heap, the Visual C++ memory leak detector will report memory leaks at the
691end of the program run. The easiest way to avoid this is to use the
692`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
693statically initialized heap objects. See MSDN for more details and additional
694heap check/debug routines.
695
696
697## How can my code detect if it is running in a test?
698
699If you write code that sniffs whether it's running in a test and does different
700things accordingly, you are leaking test-only logic into production code and
701there is no easy way to ensure that the test-only code paths aren't run by
702mistake in production. Such cleverness also leads to
703[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly
704advise against the practice, and googletest doesn't provide a way to do it.
705
706In general, the recommended way to cause the code to behave differently under
707test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject
708different functionality from the test and from the production code. Since your
709production 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)
711attribute for BUILD targets helps to ensure that), there is no danger in
712accidentally running it.
713
714However, if you *really*, *really*, *really* have no choice, and if you follow
715the 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
717whether the code is under test.
718
719
720## How do I temporarily disable a test?
721
722If you have a broken test that you cannot fix right away, you can add the
723DISABLED_ prefix to its name. This will exclude it from execution. This is
724better than commenting out the code or using #if 0, as disabled tests are still
725compiled (and thus won't rot).
726
727To include disabled tests in test execution, just invoke the test program with
728the --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
732Yes.
733
734The rule is **all test methods in the same test case must use the same fixture
735class.** This means that the following is **allowed** because both tests use the
736same fixture class (`::testing::Test`).
737
738```c++
739namespace foo {
740TEST(CoolTest, DoSomething) {
741  SUCCEED();
742}
743}  // namespace foo
744
745namespace bar {
746TEST(CoolTest, DoSomething) {
747  SUCCEED();
748}
749}  // namespace bar
750```
751
752However, the following code is **not allowed** and will produce a runtime error
753from googletest because the test methods are using different test fixture
754classes with the same test case name.
755
756```c++
757namespace foo {
758class CoolTest : public ::testing::Test {};  // Fixture foo::CoolTest
759TEST_F(CoolTest, DoSomething) {
760  SUCCEED();
761}
762}  // namespace foo
763
764namespace bar {
765class CoolTest : public ::testing::Test {};  // Fixture: bar::CoolTest
766TEST_F(CoolTest, DoSomething) {
767  SUCCEED();
768}
769}  // namespace bar
770```
771