Debian Codegraph @

src/external/googletest/docs/faq.md

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