[Gtest][Fixed build issues for the build failures of dependent modules]
[platform/upstream/gtest.git] / docs / V1_6_FAQ.md
1
2
3 If you cannot find the answer to your question here, and you have read
4 [Primer](V1_6_Primer.md) and [AdvancedGuide](V1_6_AdvancedGuide.md), send it to
5 googletestframework@googlegroups.com.
6
7 ## Why should I use Google Test instead of my favorite C++ testing framework? ##
8
9 First, let us say clearly that we don't want to get into the debate of
10 which C++ testing framework is **the best**.  There exist many fine
11 frameworks for writing C++ tests, and we have tremendous respect for
12 the developers and users of them.  We don't think there is (or will
13 be) a single best framework - you have to pick the right tool for the
14 particular task you are tackling.
15
16 We created Google Test because we couldn't find the right combination
17 of features and conveniences in an existing framework to satisfy _our_
18 needs.  The following is a list of things that _we_ like about Google
19 Test.  We don't claim them to be unique to Google Test - rather, the
20 combination of them makes Google Test the choice for us.  We hope this
21 list can help you decide whether it is for you too.
22
23   * Google Test is designed to be portable: it doesn't require exceptions or RTTI; it works around various bugs in various compilers and environments; etc.  As a result, it works on Linux, Mac OS X, Windows and several embedded operating systems.
24   * Nonfatal assertions (`EXPECT_*`) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle.
25   * It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. `ASSERT_EQ(5, Foo(i)) << " where i = " << i;`.  It doesn't require a new set of macros or special functions.
26   * Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them.
27   * Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions.
28   * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop.
29   * You can decide which tests to run using name patterns.  This saves time when you want to quickly reproduce a test failure.
30   * Google Test can generate XML test result reports that can be parsed by popular continuous build system like Hudson.
31   * Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like [global test environments](V1_6_AdvancedGuide.md#Global_Set-Up_and_Tear-Down) and tests parameterized by [values](V1_6_AdvancedGuide.md#value-parameterized-tests) or [types](V1_6_AdvancedGuide.md#typed-tests), Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself.  In particular, you can:
32     * expand your testing vocabulary by defining [custom predicates](V1_6_AdvancedGuide.md#predicate-assertions-for-better-error-messages),
33     * teach Google Test how to [print your types](V1_6_AdvancedGuide.md#teaching-google-test-how-to-print-your-values),
34     * define your own testing macros or utilities and verify them using Google Test's [Service Provider Interface](V1_6_AdvancedGuide.md#catching-failures), and
35     * reflect on the test cases or change the test output format by intercepting the [test events](V1_6_AdvancedGuide.md#extending-google-test-by-handling-test-events).
36
37 ## I'm getting warnings when compiling Google Test.  Would you fix them? ##
38
39 We strive to minimize compiler warnings Google Test generates.  Before releasing a new version, we test to make sure that it doesn't generate warnings when compiled using its CMake script on Windows, Linux, and Mac OS.
40
41 Unfortunately, this doesn't mean you are guaranteed to see no warnings when compiling Google Test in your environment:
42
43   * You may be using a different compiler as we use, or a different version of the same compiler.  We cannot possibly test for all compilers.
44   * You may be compiling on a different platform as we do.
45   * Your project may be using different compiler flags as we do.
46
47 It is not always possible to make Google Test warning-free for everyone.  Or, it may not be desirable if the warning is rarely enabled and fixing the violations makes the code more complex.
48
49 If you see warnings when compiling Google Test, we suggest that you use the `-isystem` flag (assuming your are using GCC) to mark Google Test headers as system headers.  That'll suppress warnings from Google Test headers.
50
51 ## Why should not test case names and test names contain underscore? ##
52
53 Underscore (`_`) is special, as C++ reserves the following to be used by
54 the compiler and the standard library:
55
56   1. any identifier that starts with an `_` followed by an upper-case letter, and
57   1. any identifier that containers two consecutive underscores (i.e. `__`) _anywhere_ in its name.
58
59 User code is _prohibited_ from using such identifiers.
60
61 Now let's look at what this means for `TEST` and `TEST_F`.
62
63 Currently `TEST(TestCaseName, TestName)` generates a class named
64 `TestCaseName_TestName_Test`.  What happens if `TestCaseName` or `TestName`
65 contains `_`?
66
67   1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus invalid.
68   1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get `Foo__TestName_Test`, which is invalid.
69   1. If `TestName` starts with an `_` (say, `_Bar`), we get `TestCaseName__Bar_Test`, which is invalid.
70   1. If `TestName` ends with an `_` (say, `Bar_`), we get `TestCaseName_Bar__Test`, which is invalid.
71
72 So clearly `TestCaseName` and `TestName` cannot start or end with `_`
73 (Actually, `TestCaseName` can start with `_` -- as long as the `_` isn't
74 followed by an upper-case letter.  But that's getting complicated.  So
75 for simplicity we just say that it cannot start with `_`.).
76
77 It may seem fine for `TestCaseName` and `TestName` to contain `_` in the
78 middle.  However, consider this:
79 ```
80 TEST(Time, Flies_Like_An_Arrow) { ... }
81 TEST(Time_Flies, Like_An_Arrow) { ... }
82 ```
83
84 Now, the two `TEST`s will both generate the same class
85 (`Time_Files_Like_An_Arrow_Test`).  That's not good.
86
87 So for simplicity, we just ask the users to avoid `_` in `TestCaseName`
88 and `TestName`.  The rule is more constraining than necessary, but it's
89 simple and easy to remember.  It also gives Google Test some wiggle
90 room in case its implementation needs to change in the future.
91
92 If you violate the rule, there may not be immediately consequences,
93 but your test may (just may) break with a new compiler (or a new
94 version of the compiler you are using) or with a new version of Google
95 Test.  Therefore it's best to follow the rule.
96
97 ## Why is it not recommended to install a pre-compiled copy of Google Test (for example, into /usr/local)? ##
98
99 In the early days, we said that you could install
100 compiled Google Test libraries on `*`nix systems using `make install`.
101 Then every user of your machine can write tests without
102 recompiling Google Test.
103
104 This seemed like a good idea, but it has a
105 got-cha: every user needs to compile his tests using the _same_ compiler
106 flags used to compile the installed Google Test libraries; otherwise
107 he may run into undefined behaviors (i.e. the tests can behave
108 strangely and may even crash for no obvious reasons).
109
110 Why?  Because C++ has this thing called the One-Definition Rule: if
111 two C++ source files contain different definitions of the same
112 class/function/variable, and you link them together, you violate the
113 rule.  The linker may or may not catch the error (in many cases it's
114 not required by the C++ standard to catch the violation).  If it
115 doesn't, you get strange run-time behaviors that are unexpected and
116 hard to debug.
117
118 If you compile Google Test and your test code using different compiler
119 flags, they may see different definitions of the same
120 class/function/variable (e.g. due to the use of `#if` in Google Test).
121 Therefore, for your sanity, we recommend to avoid installing pre-compiled
122 Google Test libraries.  Instead, each project should compile
123 Google Test itself such that it can be sure that the same flags are
124 used for both Google Test and the tests.
125
126 ## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ##
127
128 (Answered by Trevor Robinson)
129
130 Load the supplied Visual Studio solution file, either `msvc\gtest-md.sln` or
131 `msvc\gtest.sln`. Go through the migration wizard to migrate the
132 solution and project files to Visual Studio 2008. Select
133 `Configuration Manager...` from the `Build` menu. Select `<New...>` from
134 the `Active solution platform` dropdown.  Select `x64` from the new
135 platform dropdown, leave `Copy settings from` set to `Win32` and
136 `Create new project platforms` checked, then click `OK`. You now have
137 `Win32` and `x64` platform configurations, selectable from the
138 `Standard` toolbar, which allow you to toggle between building 32-bit or
139 64-bit binaries (or both at once using Batch Build).
140
141 In order to prevent build output files from overwriting one another,
142 you'll need to change the `Intermediate Directory` settings for the
143 newly created platform configuration across all the projects. To do
144 this, multi-select (e.g. using shift-click) all projects (but not the
145 solution) in the `Solution Explorer`. Right-click one of them and
146 select `Properties`. In the left pane, select `Configuration Properties`,
147 and from the `Configuration` dropdown, select `All Configurations`.
148 Make sure the selected platform is `x64`. For the
149 `Intermediate Directory` setting, change the value from
150 `$(PlatformName)\$(ConfigurationName)` to
151 `$(OutDir)\$(ProjectName)`. Click `OK` and then build the
152 solution. When the build is complete, the 64-bit binaries will be in
153 the `msvc\x64\Debug` directory.
154
155 ## Can I use Google Test on MinGW? ##
156
157 We haven't tested this ourselves, but Per Abrahamsen reported that he
158 was able to compile and install Google Test successfully when using
159 MinGW from Cygwin.  You'll need to configure it with:
160
161 `PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"`
162
163 You should be able to replace the `-mno-cygwin` option with direct links
164 to the real MinGW binaries, but we haven't tried that.
165
166 Caveats:
167
168   * There are many warnings when compiling.
169   * `make check` will produce some errors as not all tests for Google Test itself are compatible with MinGW.
170
171 We also have reports on successful cross compilation of Google Test
172 MinGW binaries on Linux using
173 [these instructions](http://wiki.wxwidgets.org/Cross-Compiling_Under_Linux#Cross-compiling_under_Linux_for_MS_Windows)
174 on the WxWidgets site.
175
176 Please contact `googletestframework@googlegroups.com` if you are
177 interested in improving the support for MinGW.
178
179 ## Why does Google Test support EXPECT\_EQ(NULL, ptr) and ASSERT\_EQ(NULL, ptr) but not EXPECT\_NE(NULL, ptr) and ASSERT\_NE(NULL, ptr)? ##
180
181 Due to some peculiarity of C++, it requires some non-trivial template
182 meta programming tricks to support using `NULL` as an argument of the
183 `EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where
184 it's most needed (otherwise we make the implementation of Google Test
185 harder to maintain and more error-prone than necessary).
186
187 The `EXPECT_EQ()` macro takes the _expected_ value as its first
188 argument and the _actual_ value as the second. It's reasonable that
189 someone wants to write `EXPECT_EQ(NULL, some_expression)`, and this
190 indeed was requested several times. Therefore we implemented it.
191
192 The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the
193 assertion fails, you already know that `ptr` must be `NULL`, so it
194 doesn't add any information to print ptr in this case. That means
195 `EXPECT_TRUE(ptr ! NULL)` works just as well.
196
197 If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll
198 have to support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`,
199 we don't have a convention on the order of the two arguments for
200 `EXPECT_NE`. This means using the template meta programming tricks
201 twice in the implementation, making it even harder to understand and
202 maintain. We believe the benefit doesn't justify the cost.
203
204 Finally, with the growth of Google Mock's [matcher](../../CookBook.md#using-matchers-in-google-test-assertions) library, we are
205 encouraging people to use the unified `EXPECT_THAT(value, matcher)`
206 syntax more often in tests. One significant advantage of the matcher
207 approach is that matchers can be easily combined to form new matchers,
208 while the `EXPECT_NE`, etc, macros cannot be easily
209 combined. Therefore we want to invest more in the matchers than in the
210 `EXPECT_XX()` macros.
211
212 ## Does Google Test support running tests in parallel? ##
213
214 Test runners tend to be tightly coupled with the build/test
215 environment, and Google Test doesn't try to solve the problem of
216 running tests in parallel.  Instead, we tried to make Google Test work
217 nicely with test runners.  For example, Google Test's XML report
218 contains the time spent on each test, and its `gtest_list_tests` and
219 `gtest_filter` flags can be used for splitting the execution of test
220 methods into multiple processes.  These functionalities can help the
221 test runner run the tests in parallel.
222
223 ## Why don't Google Test run the tests in different threads to speed things up? ##
224
225 It's difficult to write thread-safe code.  Most tests are not written
226 with thread-safety in mind, and thus may not work correctly in a
227 multi-threaded setting.
228
229 If you think about it, it's already hard to make your code work when
230 you know what other threads are doing.  It's much harder, and
231 sometimes even impossible, to make your code work when you don't know
232 what other threads are doing (remember that test methods can be added,
233 deleted, or modified after your test was written).  If you want to run
234 the tests in parallel, you'd better run them in different processes.
235
236 ## Why aren't Google Test assertions implemented using exceptions? ##
237
238 Our original motivation was to be able to use Google Test in projects
239 that disable exceptions.  Later we realized some additional benefits
240 of this approach:
241
242   1. Throwing in a destructor is undefined behavior in C++.  Not using exceptions means Google Test's assertions are safe to use in destructors.
243   1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing.
244   1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code:
245 ```
246 try { ... ASSERT_TRUE(...) ... }
247 catch (...) { ... }
248 ```
249 The above code will pass even if the `ASSERT_TRUE` throws.  While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test.
250
251 The downside of not using exceptions is that `ASSERT_*` (implemented
252 using `return`) will only abort the current function, not the current
253 `TEST`.
254
255 ## Why do we use two different macros for tests with and without fixtures? ##
256
257 Unfortunately, C++'s macro system doesn't allow us to use the same
258 macro for both cases.  One possibility is to provide only one macro
259 for tests with fixtures, and require the user to define an empty
260 fixture sometimes:
261
262 ```
263 class FooTest : public ::testing::Test {};
264
265 TEST_F(FooTest, DoesThis) { ... }
266 ```
267 or
268 ```
269 typedef ::testing::Test FooTest;
270
271 TEST_F(FooTest, DoesThat) { ... }
272 ```
273
274 Yet, many people think this is one line too many. :-) Our goal was to
275 make it really easy to write tests, so we tried to make simple tests
276 trivial to create.  That means using a separate macro for such tests.
277
278 We think neither approach is ideal, yet either of them is reasonable.
279 In the end, it probably doesn't matter much either way.
280
281 ## Why don't we use structs as test fixtures? ##
282
283 We like to use structs only when representing passive data.  This
284 distinction between structs and classes is good for documenting the
285 intent of the code's author.  Since test fixtures have logic like
286 `SetUp()` and `TearDown()`, they are better defined as classes.
287
288 ## Why are death tests implemented as assertions instead of using a test runner? ##
289
290 Our goal was to make death tests as convenient for a user as C++
291 possibly allows.  In particular:
292
293   * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect.  The death test would be written in C++, while the runner spec may or may not be.  A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative.
294   * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn.
295   * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will.  You are not limited to one death test per test method. For example, you can write something like:
296 ```
297     if (FooCondition()) {
298       ASSERT_DEATH(Bar(), "blah");
299     } else {
300       ASSERT_EQ(5, Bar());
301     }
302 ```
303 If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users.  The fewer artificial limitations the better.
304   * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information.  For example,
305 ```
306     const int count = GetCount();  // Only known at run time.
307     for (int i = 1; i <= count; i++) {
308       ASSERT_DEATH({
309         double* buffer = new double[i];
310         ... initializes buffer ...
311         Foo(buffer, i)
312       }, "blah blah");
313     }
314 ```
315 The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility.
316
317 Another interesting thing about `ASSERT_DEATH` is that it calls `fork()`
318 to create a child process to run the death test.  This is lightening
319 fast, as `fork()` uses copy-on-write pages and incurs almost zero
320 overhead, and the child process starts from the user-supplied
321 statement directly, skipping all global and local initialization and
322 any code leading to the given statement.  If you launch the child
323 process from scratch, it can take seconds just to load everything and
324 start running if the test links to many libraries dynamically.
325
326 ## My death test modifies some state, but the change seems lost after the death test finishes. Why? ##
327
328 Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
329 expected crash won't kill the test program (i.e. the parent process). As a
330 result, any in-memory side effects they incur are observable in their
331 respective sub-processes, but not in the parent process. You can think of them
332 as running in a parallel universe, more or less.
333
334 ## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? ##
335
336 If your class has a static data member:
337
338 ```
339 // foo.h
340 class Foo {
341   ...
342   static const int kBar = 100;
343 };
344 ```
345
346 You also need to define it _outside_ of the class body in `foo.cc`:
347
348 ```
349 const int Foo::kBar;  // No initializer here.
350 ```
351
352 Otherwise your code is **invalid C++**, and may break in unexpected ways. In
353 particular, using it in Google Test comparison assertions (`EXPECT_EQ`, etc)
354 will generate an "undefined reference" linker error.
355
356 ## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ##
357
358 Google Test doesn't yet have good support for this kind of tests, or
359 data-driven tests in general. We hope to be able to make improvements in this
360 area soon.
361
362 ## Can I derive a test fixture from another? ##
363
364 Yes.
365
366 Each test fixture has a corresponding and same named test case. This means only
367 one test case can use a particular fixture. Sometimes, however, multiple test
368 cases may want to use the same or slightly different fixtures. For example, you
369 may want to make sure that all of a GUI library's test cases don't leak
370 important system resources like fonts and brushes.
371
372 In Google Test, you share a fixture among test cases by putting the shared
373 logic in a base test fixture, then deriving from that base a separate fixture
374 for each test case that wants to use this common logic. You then use `TEST_F()`
375 to write tests using each derived fixture.
376
377 Typically, your code looks like this:
378
379 ```
380 // Defines a base test fixture.
381 class BaseTest : public ::testing::Test {
382   protected:
383    ...
384 };
385
386 // Derives a fixture FooTest from BaseTest.
387 class FooTest : public BaseTest {
388   protected:
389     virtual void SetUp() {
390       BaseTest::SetUp();  // Sets up the base fixture first.
391       ... additional set-up work ...
392     }
393     virtual void TearDown() {
394       ... clean-up work for FooTest ...
395       BaseTest::TearDown();  // Remember to tear down the base fixture
396                              // after cleaning up FooTest!
397     }
398     ... functions and variables for FooTest ...
399 };
400
401 // Tests that use the fixture FooTest.
402 TEST_F(FooTest, Bar) { ... }
403 TEST_F(FooTest, Baz) { ... }
404
405 ... additional fixtures derived from BaseTest ...
406 ```
407
408 If necessary, you can continue to derive test fixtures from a derived fixture.
409 Google Test has no limit on how deep the hierarchy can be.
410
411 For a complete example using derived test fixtures, see
412 [sample5](../samples/sample5_unittest.cc).
413
414 ## My compiler complains "void value not ignored as it ought to be." What does this mean? ##
415
416 You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
417 `ASSERT_*()` can only be used in `void` functions.
418
419 ## My death test hangs (or seg-faults). How do I fix it? ##
420
421 In Google Test, death tests are run in a child process and the way they work is
422 delicate. To write death tests you really need to understand how they work.
423 Please make sure you have read this.
424
425 In particular, death tests don't like having multiple threads in the parent
426 process. So the first thing you can try is to eliminate creating threads
427 outside of `EXPECT_DEATH()`.
428
429 Sometimes this is impossible as some library you must use may be creating
430 threads before `main()` is even reached. In this case, you can try to minimize
431 the chance of conflicts by either moving as many activities as possible inside
432 `EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
433 leaving as few things as possible in it. Also, you can try to set the death
434 test style to `"threadsafe"`, which is safer but slower, and see if it helps.
435
436 If you go with thread-safe death tests, remember that they rerun the test
437 program from the beginning in the child process. Therefore make sure your
438 program can run side-by-side with itself and is deterministic.
439
440 In the end, this boils down to good concurrent programming. You have to make
441 sure that there is no race conditions or dead locks in your program. No silver
442 bullet - sorry!
443
444 ## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ##
445
446 The first thing to remember is that Google Test does not reuse the
447 same test fixture object across multiple tests. For each `TEST_F`,
448 Google Test will create a fresh test fixture object, _immediately_
449 call `SetUp()`, run the test, call `TearDown()`, and then
450 _immediately_ delete the test fixture object. Therefore, there is no
451 need to write a `SetUp()` or `TearDown()` function if the constructor
452 or destructor already does the job.
453
454 You may still want to use `SetUp()/TearDown()` in the following cases:
455   * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions.
456   * The Google Test team is considering making the assertion macros throw on platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux client-side), which will eliminate the need for the user to propagate failures from a subroutine to its caller. Therefore, you shouldn't use Google Test assertions in a destructor if your code could run on such a platform.
457   * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overriden in a derived class, you have to use `SetUp()/TearDown()`.
458
459 ## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ##
460
461 If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
462 overloaded or a template, the compiler will have trouble figuring out which
463 overloaded version it should use. `ASSERT_PRED_FORMAT*` and
464 `EXPECT_PRED_FORMAT*` don't have this problem.
465
466 If you see this error, you might want to switch to
467 `(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
468 message. If, however, that is not an option, you can resolve the problem by
469 explicitly telling the compiler which version to pick.
470
471 For example, suppose you have
472
473 ```
474 bool IsPositive(int n) {
475   return n > 0;
476 }
477 bool IsPositive(double x) {
478   return x > 0;
479 }
480 ```
481
482 you will get a compiler error if you write
483
484 ```
485 EXPECT_PRED1(IsPositive, 5);
486 ```
487
488 However, this will work:
489
490 ```
491 EXPECT_PRED1(*static_cast<bool (*)(int)>*(IsPositive), 5);
492 ```
493
494 (The stuff inside the angled brackets for the `static_cast` operator is the
495 type of the function pointer for the `int`-version of `IsPositive()`.)
496
497 As another example, when you have a template function
498
499 ```
500 template <typename T>
501 bool IsNegative(T x) {
502   return x < 0;
503 }
504 ```
505
506 you can use it in a predicate assertion like this:
507
508 ```
509 ASSERT_PRED1(IsNegative*<int>*, -5);
510 ```
511
512 Things are more interesting if your template has more than one parameters. The
513 following won't compile:
514
515 ```
516 ASSERT_PRED2(*GreaterThan<int, int>*, 5, 0);
517 ```
518
519
520 as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments,
521 which is one more than expected. The workaround is to wrap the predicate
522 function in parentheses:
523
524 ```
525 ASSERT_PRED2(*(GreaterThan<int, int>)*, 5, 0);
526 ```
527
528
529 ## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ##
530
531 Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
532 instead of
533
534 ```
535 return RUN_ALL_TESTS();
536 ```
537
538 they write
539
540 ```
541 RUN_ALL_TESTS();
542 ```
543
544 This is wrong and dangerous. A test runner needs to see the return value of
545 `RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()`
546 function ignores it, your test will be considered successful even if it has a
547 Google Test assertion failure. Very bad.
548
549 To help the users avoid this dangerous bug, the implementation of
550 `RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is
551 ignored. If you see this warning, the fix is simple: just make sure its value
552 is used as the return value of `main()`.
553
554 ## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ##
555
556 Due to a peculiarity of C++, in order to support the syntax for streaming
557 messages to an `ASSERT_*`, e.g.
558
559 ```
560 ASSERT_EQ(1, Foo()) << "blah blah" << foo;
561 ```
562
563 we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
564 `ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
565 content of your constructor/destructor to a private void member function, or
566 switch to `EXPECT_*()` if that works. This section in the user's guide explains
567 it.
568
569 ## My set-up function is not called. Why? ##
570
571 C++ is case-sensitive. It should be spelled as `SetUp()`.  Did you
572 spell it as `Setup()`?
573
574 Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and
575 wonder why it's never called.
576
577 ## How do I jump to the line of a failure in Emacs directly? ##
578
579 Google Test's failure message format is understood by Emacs and many other
580 IDEs, like acme and XCode. If a Google Test message is in a compilation buffer
581 in Emacs, then it's clickable. You can now hit `enter` on a message to jump to
582 the corresponding source code, or use `C-x `` to jump to the next failure.
583
584 ## 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. ##
585
586 You don't have to. Instead of
587
588 ```
589 class FooTest : public BaseTest {};
590
591 TEST_F(FooTest, Abc) { ... }
592 TEST_F(FooTest, Def) { ... }
593
594 class BarTest : public BaseTest {};
595
596 TEST_F(BarTest, Abc) { ... }
597 TEST_F(BarTest, Def) { ... }
598 ```
599
600 you can simply `typedef` the test fixtures:
601 ```
602 typedef BaseTest FooTest;
603
604 TEST_F(FooTest, Abc) { ... }
605 TEST_F(FooTest, Def) { ... }
606
607 typedef BaseTest BarTest;
608
609 TEST_F(BarTest, Abc) { ... }
610 TEST_F(BarTest, Def) { ... }
611 ```
612
613 ## The Google Test output is buried in a whole bunch of log messages. What do I do? ##
614
615 The Google Test output is meant to be a concise and human-friendly report. If
616 your test generates textual output itself, it will mix with the Google Test
617 output, making it hard to read. However, there is an easy solution to this
618 problem.
619
620 Since most log messages go to stderr, we decided to let Google Test output go
621 to stdout. This way, you can easily separate the two using redirection. For
622 example:
623 ```
624 ./my_test > googletest_output.txt
625 ```
626
627 ## Why should I prefer test fixtures over global variables? ##
628
629 There are several good reasons:
630   1. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other.
631   1. Global variables pollute the global namespace.
632   1. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common.
633
634 ## How do I test private class members without writing FRIEND\_TEST()s? ##
635
636 You should try to write testable code, which means classes should be easily
637 tested from their public interface. One way to achieve this is the Pimpl idiom:
638 you move all private members of a class into a helper class, and make all
639 members of the helper class public.
640
641 You have several other options that don't require using `FRIEND_TEST`:
642   * Write the tests as members of the fixture class:
643 ```
644 class Foo {
645   friend class FooTest;
646   ...
647 };
648
649 class FooTest : public ::testing::Test {
650  protected:
651   ...
652   void Test1() {...} // This accesses private members of class Foo.
653   void Test2() {...} // So does this one.
654 };
655
656 TEST_F(FooTest, Test1) {
657   Test1();
658 }
659
660 TEST_F(FooTest, Test2) {
661   Test2();
662 }
663 ```
664   * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests:
665 ```
666 class Foo {
667   friend class FooTest;
668   ...
669 };
670
671 class FooTest : public ::testing::Test {
672  protected:
673   ...
674   T1 get_private_member1(Foo* obj) {
675     return obj->private_member1_;
676   }
677 };
678
679 TEST_F(FooTest, Test1) {
680   ...
681   get_private_member1(x)
682   ...
683 }
684 ```
685   * If the methods are declared **protected**, you can change their access level in a test-only subclass:
686 ```
687 class YourClass {
688   ...
689  protected: // protected access for testability.
690   int DoSomethingReturningInt();
691   ...
692 };
693
694 // in the your_class_test.cc file:
695 class TestableYourClass : public YourClass {
696   ...
697  public: using YourClass::DoSomethingReturningInt; // changes access rights
698   ...
699 };
700
701 TEST_F(YourClassTest, DoSomethingTest) {
702   TestableYourClass obj;
703   assertEquals(expected_value, obj.DoSomethingReturningInt());
704 }
705 ```
706
707 ## How do I test private class static members without writing FRIEND\_TEST()s? ##
708
709 We find private static methods clutter the header file.  They are
710 implementation details and ideally should be kept out of a .h. So often I make
711 them free functions instead.
712
713 Instead of:
714 ```
715 // foo.h
716 class Foo {
717   ...
718  private:
719   static bool Func(int n);
720 };
721
722 // foo.cc
723 bool Foo::Func(int n) { ... }
724
725 // foo_test.cc
726 EXPECT_TRUE(Foo::Func(12345));
727 ```
728
729 You probably should better write:
730 ```
731 // foo.h
732 class Foo {
733   ...
734 };
735
736 // foo.cc
737 namespace internal {
738   bool Func(int n) { ... }
739 }
740
741 // foo_test.cc
742 namespace internal {
743   bool Func(int n);
744 }
745
746 EXPECT_TRUE(internal::Func(12345));
747 ```
748
749 ## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ##
750
751 No. You can use a feature called [value-parameterized tests](V1_6_AdvancedGuide.md#Value_Parameterized_Tests) which
752 lets you repeat your tests with different parameters, without defining it more than once.
753
754 ## How do I test a file that defines main()? ##
755
756 To test a `foo.cc` file, you need to compile and link it into your unit test
757 program. However, when the file contains a definition for the `main()`
758 function, it will clash with the `main()` of your unit test, and will result in
759 a build error.
760
761 The right solution is to split it into three files:
762   1. `foo.h` which contains the declarations,
763   1. `foo.cc` which contains the definitions except `main()`, and
764   1. `foo_main.cc` which contains nothing but the definition of `main()`.
765
766 Then `foo.cc` can be easily tested.
767
768 If you are adding tests to an existing file and don't want an intrusive change
769 like this, there is a hack: just include the entire `foo.cc` file in your unit
770 test. For example:
771 ```
772 // File foo_unittest.cc
773
774 // The headers section
775 ...
776
777 // Renames main() in foo.cc to make room for the unit test main()
778 #define main FooMain
779
780 #include "a/b/foo.cc"
781
782 // The tests start here.
783 ...
784 ```
785
786
787 However, please remember this is a hack and should only be used as the last
788 resort.
789
790 ## What can the statement argument in ASSERT\_DEATH() be? ##
791
792 `ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used
793 wherever `_statement_` is valid. So basically `_statement_` can be any C++
794 statement that makes sense in the current context. In particular, it can
795 reference global and/or local variables, and can be:
796   * a simple function call (often the case),
797   * a complex expression, or
798   * a compound statement.
799
800 > Some examples are shown here:
801
802 ```
803 // A death test can be a simple function call.
804 TEST(MyDeathTest, FunctionCall) {
805   ASSERT_DEATH(Xyz(5), "Xyz failed");
806 }
807
808 // Or a complex expression that references variables and functions.
809 TEST(MyDeathTest, ComplexExpression) {
810   const bool c = Condition();
811   ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
812                "(Func1|Method) failed");
813 }
814
815 // Death assertions can be used any where in a function. In
816 // particular, they can be inside a loop.
817 TEST(MyDeathTest, InsideLoop) {
818   // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
819   for (int i = 0; i < 5; i++) {
820     EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
821                    ::testing::Message() << "where i is " << i);
822   }
823 }
824
825 // A death assertion can contain a compound statement.
826 TEST(MyDeathTest, CompoundStatement) {
827   // Verifies that at lease one of Bar(0), Bar(1), ..., and
828   // Bar(4) dies.
829   ASSERT_DEATH({
830     for (int i = 0; i < 5; i++) {
831       Bar(i);
832     }
833   },
834   "Bar has \\d+ errors");}
835 ```
836
837 `googletest_unittest.cc` contains more examples if you are interested.
838
839 ## What syntax does the regular expression in ASSERT\_DEATH use? ##
840
841 On POSIX systems, Google Test uses the POSIX Extended regular
842 expression syntax
843 (http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
844 On Windows, it uses a limited variant of regular expression
845 syntax. For more details, see the
846 [regular expression syntax](V1_6_AdvancedGuide.md#Regular_Expression_Syntax).
847
848 ## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ##
849
850 Google Test needs to be able to create objects of your test fixture class, so
851 it must have a default constructor. Normally the compiler will define one for
852 you. However, there are cases where you have to define your own:
853   * If you explicitly declare a non-default constructor for class `Foo`, then you need to define a default constructor, even if it would be empty.
854   * If `Foo` has a const non-static data member, then you have to define the default constructor _and_ initialize the const member in the initializer list of the constructor. (Early versions of `gcc` doesn't force you to initialize the const member. It's a bug that has been fixed in `gcc 4`.)
855
856 ## Why does ASSERT\_DEATH complain about previous threads that were already joined? ##
857
858 With the Linux pthread library, there is no turning back once you cross the
859 line from single thread to multiple threads. The first time you create a
860 thread, a manager thread is created in addition, so you get 3, not 2, threads.
861 Later when the thread you create joins the main thread, the thread count
862 decrements by 1, but the manager thread will never be killed, so you still have
863 2 threads, which means you cannot safely run a death test.
864
865 The new NPTL thread library doesn't suffer from this problem, as it doesn't
866 create a manager thread. However, if you don't control which machine your test
867 runs on, you shouldn't depend on this.
868
869 ## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ##
870
871 Google Test does not interleave tests from different test cases. That is, it
872 runs all tests in one test case first, and then runs all tests in the next test
873 case, and so on. Google Test does this because it needs to set up a test case
874 before the first test in it is run, and tear it down afterwords. Splitting up
875 the test case would require multiple set-up and tear-down processes, which is
876 inefficient and makes the semantics unclean.
877
878 If we were to determine the order of tests based on test name instead of test
879 case name, then we would have a problem with the following situation:
880
881 ```
882 TEST_F(FooTest, AbcDeathTest) { ... }
883 TEST_F(FooTest, Uvw) { ... }
884
885 TEST_F(BarTest, DefDeathTest) { ... }
886 TEST_F(BarTest, Xyz) { ... }
887 ```
888
889 Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
890 interleave tests from different test cases, we need to run all tests in the
891 `FooTest` case before running any test in the `BarTest` case. This contradicts
892 with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
893
894 ## But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? ##
895
896 You don't have to, but if you like, you may split up the test case into
897 `FooTest` and `FooDeathTest`, where the names make it clear that they are
898 related:
899
900 ```
901 class FooTest : public ::testing::Test { ... };
902
903 TEST_F(FooTest, Abc) { ... }
904 TEST_F(FooTest, Def) { ... }
905
906 typedef FooTest FooDeathTest;
907
908 TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
909 TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
910 ```
911
912 ## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ##
913
914 If you use a user-defined type `FooType` in an assertion, you must make sure
915 there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
916 defined such that we can print a value of `FooType`.
917
918 In addition, if `FooType` is declared in a name space, the `<<` operator also
919 needs to be defined in the _same_ name space.
920
921 ## How do I suppress the memory leak messages on Windows? ##
922
923 Since the statically initialized Google Test singleton requires allocations on
924 the heap, the Visual C++ memory leak detector will report memory leaks at the
925 end of the program run. The easiest way to avoid this is to use the
926 `_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
927 statically initialized heap objects. See MSDN for more details and additional
928 heap check/debug routines.
929
930 ## I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! ##
931
932 You may get a number of the following linker error or warnings if you
933 attempt to link your test project with the Google Test library when
934 your project and the are not built using the same compiler settings.
935
936   * LNK2005: symbol already defined in object
937   * LNK4217: locally defined symbol 'symbol' imported in function 'function'
938   * LNK4049: locally defined symbol 'symbol' imported
939
940 The Google Test project (gtest.vcproj) has the Runtime Library option
941 set to /MT (use multi-threaded static libraries, /MTd for debug). If
942 your project uses something else, for example /MD (use multi-threaded
943 DLLs, /MDd for debug), you need to change the setting in the Google
944 Test project to match your project's.
945
946 To update this setting open the project properties in the Visual
947 Studio IDE then select the branch Configuration Properties | C/C++ |
948 Code Generation and change the option "Runtime Library".  You may also try
949 using gtest-md.vcproj instead of gtest.vcproj.
950
951 ## I put my tests in a library and Google Test doesn't run them. What's happening? ##
952 Have you read a
953 [warning](V1_6_Primer.md#important-note-for-visual-c-users) on
954 the Google Test Primer page?
955
956 ## I want to use Google Test with Visual Studio but don't know where to start. ##
957 Many people are in your position and one of the posted his solution to
958 our mailing list. Here is his link:
959 http://hassanjamilahmad.blogspot.com/2009/07/gtest-starters-help.html.
960
961 ## I am seeing compile errors mentioning std::type\_traits when I try to use Google Test on Solaris. ##
962 Google Test uses parts of the standard C++ library that SunStudio does not support.
963 Our users reported success using alternative implementations. Try running the build after runing this commad:
964
965 `export CC=cc CXX=CC CXXFLAGS='-library=stlport4'`
966
967 ## How can my code detect if it is running in a test? ##
968
969 If you write code that sniffs whether it's running in a test and does
970 different things accordingly, you are leaking test-only logic into
971 production code and there is no easy way to ensure that the test-only
972 code paths aren't run by mistake in production.  Such cleverness also
973 leads to
974 [Heisenbugs](http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug).
975 Therefore we strongly advise against the practice, and Google Test doesn't
976 provide a way to do it.
977
978 In general, the recommended way to cause the code to behave
979 differently under test is [dependency injection](http://jamesshore.com/Blog/Dependency-Injection-Demystified.html).
980 You can inject different functionality from the test and from the
981 production code.  Since your production code doesn't link in the
982 for-test logic at all, there is no danger in accidentally running it.
983
984 However, if you _really_, _really_, _really_ have no choice, and if
985 you follow the rule of ending your test program names with `_test`,
986 you can use the _horrible_ hack of sniffing your executable name
987 (`argv[0]` in `main()`) to know whether the code is under test.
988
989 ## Google Test defines a macro that clashes with one defined by another library. How do I deal with that? ##
990
991 In C++, macros don't obey namespaces.  Therefore two libraries that
992 both define a macro of the same name will clash if you `#include` both
993 definitions.  In case a Google Test macro clashes with another
994 library, you can force Google Test to rename its macro to avoid the
995 conflict.
996
997 Specifically, if both Google Test and some other code define macro
998 `FOO`, you can add
999 ```
1000   -DGTEST_DONT_DEFINE_FOO=1
1001 ```
1002 to the compiler flags to tell Google Test to change the macro's name
1003 from `FOO` to `GTEST_FOO`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
1004 ```
1005   GTEST_TEST(SomeTest, DoesThis) { ... }
1006 ```
1007 instead of
1008 ```
1009   TEST(SomeTest, DoesThis) { ... }
1010 ```
1011 in order to define a test.
1012
1013 Currently, the following `TEST`, `FAIL`, `SUCCEED`, and the basic comparison assertion macros can have alternative names. You can see the full list of covered macros [here](http://www.google.com/codesearch?q=if+!GTEST_DONT_DEFINE_\w%2B+package:http://googletest\.googlecode\.com+file:/include/gtest/gtest.h). More information can be found in the "Avoiding Macro Name Clashes" section of the README file.
1014
1015 ## My question is not covered in your FAQ! ##
1016
1017 If you cannot find the answer to your question in this FAQ, there are
1018 some other resources you can use:
1019
1020   1. read other [wiki pages](http://code.google.com/p/googletest/w/list),
1021   1. search the mailing list [archive](http://groups.google.com/group/googletestframework/topics),
1022   1. ask it on [googletestframework@googlegroups.com](mailto:googletestframework@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googletestframework) before you can post.).
1023
1024 Please note that creating an issue in the
1025 [issue tracker](http://code.google.com/p/googletest/issues/list) is _not_
1026 a good way to get your answer, as it is monitored infrequently by a
1027 very small number of people.
1028
1029 When asking a question, it's helpful to provide as much of the
1030 following information as possible (people cannot help you if there's
1031 not enough information in your question):
1032
1033   * the version (or the revision number if you check out from SVN directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version),
1034   * your operating system,
1035   * the name and version of your compiler,
1036   * the complete command line flags you give to your compiler,
1037   * the complete compiler error messages (if the question is about compilation),
1038   * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.