3 If you cannot find the answer to your question here, and you have read
4 [Primer](Primer.md) and [AdvancedGuide](AdvancedGuide.md), send it to
5 googletestframework@googlegroups.com.
7 ## Why should I use Google Test instead of my favorite C++ testing framework? ##
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.
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.
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](AdvancedGuide.md#global-set-up-and-tear-down) and tests parameterized by [values](AdvancedGuide.md#value-parameterized-tests) or [types](docs/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](AdvancedGuide.md#predicate-assertions-for-better-error-messages),
33 * teach Google Test how to [print your types](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](AdvancedGuide.md#catching-failures), and
35 * reflect on the test cases or change the test output format by intercepting the [test events](AdvancedGuide.md#extending-google-test-by-handling-test-events).
37 ## I'm getting warnings when compiling Google Test. Would you fix them? ##
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.
41 Unfortunately, this doesn't mean you are guaranteed to see no warnings when compiling Google Test in your environment:
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.
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.
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.
51 ## Why should not test case names and test names contain underscore? ##
53 Underscore (`_`) is special, as C++ reserves the following to be used by
54 the compiler and the standard library:
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.
59 User code is _prohibited_ from using such identifiers.
61 Now let's look at what this means for `TEST` and `TEST_F`.
63 Currently `TEST(TestCaseName, TestName)` generates a class named
64 `TestCaseName_TestName_Test`. What happens if `TestCaseName` or `TestName`
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.
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 `_`.).
77 It may seem fine for `TestCaseName` and `TestName` to contain `_` in the
78 middle. However, consider this:
80 TEST(Time, Flies_Like_An_Arrow) { ... }
81 TEST(Time_Flies, Like_An_Arrow) { ... }
84 Now, the two `TEST`s will both generate the same class
85 (`Time_Files_Like_An_Arrow_Test`). That's not good.
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.
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.
97 ## Why is it not recommended to install a pre-compiled copy of Google Test (for example, into /usr/local)? ##
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.
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).
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
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.
126 ## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ##
128 (Answered by Trevor Robinson)
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).
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.
155 ## Can I use Google Test on MinGW? ##
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:
161 `PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"`
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.
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.
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.
176 Please contact `googletestframework@googlegroups.com` if you are
177 interested in improving the support for MinGW.
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)? ##
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).
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.
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.
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.
204 Finally, with the growth of Google Mock's [matcher](../../googlemock/docs/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.
212 ## Does Google Test support running tests in parallel? ##
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.
223 ## Why don't Google Test run the tests in different threads to speed things up? ##
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.
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.
236 ## Why aren't Google Test assertions implemented using exceptions? ##
238 Our original motivation was to be able to use Google Test in projects
239 that disable exceptions. Later we realized some additional benefits
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:
246 try { ... ASSERT_TRUE(...) ... }
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.
251 The downside of not using exceptions is that `ASSERT_*` (implemented
252 using `return`) will only abort the current function, not the current
255 ## Why do we use two different macros for tests with and without fixtures? ##
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
263 class FooTest : public ::testing::Test {};
265 TEST_F(FooTest, DoesThis) { ... }
269 typedef ::testing::Test FooTest;
271 TEST_F(FooTest, DoesThat) { ... }
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.
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.
281 ## Why don't we use structs as test fixtures? ##
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.
288 ## Why are death tests implemented as assertions instead of using a test runner? ##
290 Our goal was to make death tests as convenient for a user as C++
291 possibly allows. In particular:
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:
297 if (FooCondition()) {
298 ASSERT_DEATH(Bar(), "blah");
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,
306 const int count = GetCount(); // Only known at run time.
307 for (int i = 1; i <= count; i++) {
309 double* buffer = new double[i];
310 ... initializes buffer ...
315 The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility.
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.
326 ## My death test modifies some state, but the change seems lost after the death test finishes. Why? ##
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.
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? ##
336 If your class has a static data member:
342 static const int kBar = 100;
346 You also need to define it _outside_ of the class body in `foo.cc`:
349 const int Foo::kBar; // No initializer here.
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.
356 ## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ##
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
362 ## Can I derive a test fixture from another? ##
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.
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.
377 Typically, your code looks like this:
380 // Defines a base test fixture.
381 class BaseTest : public ::testing::Test {
386 // Derives a fixture FooTest from BaseTest.
387 class FooTest : public BaseTest {
389 virtual void SetUp() {
390 BaseTest::SetUp(); // Sets up the base fixture first.
391 ... additional set-up work ...
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!
398 ... functions and variables for FooTest ...
401 // Tests that use the fixture FooTest.
402 TEST_F(FooTest, Bar) { ... }
403 TEST_F(FooTest, Baz) { ... }
405 ... additional fixtures derived from BaseTest ...
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.
411 For a complete example using derived test fixtures, see
412 [sample5](../samples/sample5_unittest.cc).
414 ## My compiler complains "void value not ignored as it ought to be." What does this mean? ##
416 You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
417 `ASSERT_*()` can only be used in `void` functions.
419 ## My death test hangs (or seg-faults). How do I fix it? ##
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.
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()`.
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.
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.
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
444 ## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ##
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 body, call `TearDown()`, and then
450 _immediately_ delete the test fixture object.
452 When you need to write per-test set-up and tear-down logic, you have
453 the choice between using the test fixture constructor/destructor or
454 `SetUp()/TearDown()`. The former is usually preferred, as it has the
457 * By initializing a member variable in the constructor, we have the option to make it `const`, which helps prevent accidental changes to its value and makes the tests more obviously correct.
458 * In case we need to subclass the test fixture class, the subclass' constructor is guaranteed to call the base class' constructor first, and the subclass' destructor is guaranteed to call the base class' destructor afterward. With `SetUp()/TearDown()`, a subclass may make the mistake of forgetting to call the base class' `SetUp()/TearDown()` or call them at the wrong moment.
460 You may still want to use `SetUp()/TearDown()` in the following rare cases:
461 * 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.
462 * The assertion macros throw an exception when flag `--gtest_throw_on_failure` is specified. Therefore, you shouldn't use Google Test assertions in a destructor if you plan to run your tests with this flag.
463 * 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()`.
465 ## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ##
467 If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
468 overloaded or a template, the compiler will have trouble figuring out which
469 overloaded version it should use. `ASSERT_PRED_FORMAT*` and
470 `EXPECT_PRED_FORMAT*` don't have this problem.
472 If you see this error, you might want to switch to
473 `(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
474 message. If, however, that is not an option, you can resolve the problem by
475 explicitly telling the compiler which version to pick.
477 For example, suppose you have
480 bool IsPositive(int n) {
483 bool IsPositive(double x) {
488 you will get a compiler error if you write
491 EXPECT_PRED1(IsPositive, 5);
494 However, this will work:
497 EXPECT_PRED1(*static_cast<bool (*)(int)>*(IsPositive), 5);
500 (The stuff inside the angled brackets for the `static_cast` operator is the
501 type of the function pointer for the `int`-version of `IsPositive()`.)
503 As another example, when you have a template function
506 template <typename T>
507 bool IsNegative(T x) {
512 you can use it in a predicate assertion like this:
515 ASSERT_PRED1(IsNegative*<int>*, -5);
518 Things are more interesting if your template has more than one parameters. The
519 following won't compile:
522 ASSERT_PRED2(*GreaterThan<int, int>*, 5, 0);
526 as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments,
527 which is one more than expected. The workaround is to wrap the predicate
528 function in parentheses:
531 ASSERT_PRED2(*(GreaterThan<int, int>)*, 5, 0);
535 ## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ##
537 Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
541 return RUN_ALL_TESTS();
550 This is wrong and dangerous. A test runner needs to see the return value of
551 `RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()`
552 function ignores it, your test will be considered successful even if it has a
553 Google Test assertion failure. Very bad.
555 To help the users avoid this dangerous bug, the implementation of
556 `RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is
557 ignored. If you see this warning, the fix is simple: just make sure its value
558 is used as the return value of `main()`.
560 ## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ##
562 Due to a peculiarity of C++, in order to support the syntax for streaming
563 messages to an `ASSERT_*`, e.g.
566 ASSERT_EQ(1, Foo()) << "blah blah" << foo;
569 we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
570 `ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
571 content of your constructor/destructor to a private void member function, or
572 switch to `EXPECT_*()` if that works. This section in the user's guide explains
575 ## My set-up function is not called. Why? ##
577 C++ is case-sensitive. It should be spelled as `SetUp()`. Did you
578 spell it as `Setup()`?
580 Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and
581 wonder why it's never called.
583 ## How do I jump to the line of a failure in Emacs directly? ##
585 Google Test's failure message format is understood by Emacs and many other
586 IDEs, like acme and XCode. If a Google Test message is in a compilation buffer
587 in Emacs, then it's clickable. You can now hit `enter` on a message to jump to
588 the corresponding source code, or use `C-x `` to jump to the next failure.
590 ## 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. ##
592 You don't have to. Instead of
595 class FooTest : public BaseTest {};
597 TEST_F(FooTest, Abc) { ... }
598 TEST_F(FooTest, Def) { ... }
600 class BarTest : public BaseTest {};
602 TEST_F(BarTest, Abc) { ... }
603 TEST_F(BarTest, Def) { ... }
606 you can simply `typedef` the test fixtures:
608 typedef BaseTest FooTest;
610 TEST_F(FooTest, Abc) { ... }
611 TEST_F(FooTest, Def) { ... }
613 typedef BaseTest BarTest;
615 TEST_F(BarTest, Abc) { ... }
616 TEST_F(BarTest, Def) { ... }
619 ## The Google Test output is buried in a whole bunch of log messages. What do I do? ##
621 The Google Test output is meant to be a concise and human-friendly report. If
622 your test generates textual output itself, it will mix with the Google Test
623 output, making it hard to read. However, there is an easy solution to this
626 Since most log messages go to stderr, we decided to let Google Test output go
627 to stdout. This way, you can easily separate the two using redirection. For
630 ./my_test > googletest_output.txt
633 ## Why should I prefer test fixtures over global variables? ##
635 There are several good reasons:
636 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.
637 1. Global variables pollute the global namespace.
638 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.
640 ## How do I test private class members without writing FRIEND\_TEST()s? ##
642 You should try to write testable code, which means classes should be easily
643 tested from their public interface. One way to achieve this is the Pimpl idiom:
644 you move all private members of a class into a helper class, and make all
645 members of the helper class public.
647 You have several other options that don't require using `FRIEND_TEST`:
648 * Write the tests as members of the fixture class:
651 friend class FooTest;
655 class FooTest : public ::testing::Test {
658 void Test1() {...} // This accesses private members of class Foo.
659 void Test2() {...} // So does this one.
662 TEST_F(FooTest, Test1) {
666 TEST_F(FooTest, Test2) {
670 * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests:
673 friend class FooTest;
677 class FooTest : public ::testing::Test {
680 T1 get_private_member1(Foo* obj) {
681 return obj->private_member1_;
685 TEST_F(FooTest, Test1) {
687 get_private_member1(x)
691 * If the methods are declared **protected**, you can change their access level in a test-only subclass:
695 protected: // protected access for testability.
696 int DoSomethingReturningInt();
700 // in the your_class_test.cc file:
701 class TestableYourClass : public YourClass {
703 public: using YourClass::DoSomethingReturningInt; // changes access rights
707 TEST_F(YourClassTest, DoSomethingTest) {
708 TestableYourClass obj;
709 assertEquals(expected_value, obj.DoSomethingReturningInt());
713 ## How do I test private class static members without writing FRIEND\_TEST()s? ##
715 We find private static methods clutter the header file. They are
716 implementation details and ideally should be kept out of a .h. So often I make
717 them free functions instead.
725 static bool Func(int n);
729 bool Foo::Func(int n) { ... }
732 EXPECT_TRUE(Foo::Func(12345));
735 You probably should better write:
744 bool Func(int n) { ... }
752 EXPECT_TRUE(internal::Func(12345));
755 ## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ##
757 No. You can use a feature called [value-parameterized tests](AdvancedGuide.md#Value_Parameterized_Tests) which
758 lets you repeat your tests with different parameters, without defining it more than once.
760 ## How do I test a file that defines main()? ##
762 To test a `foo.cc` file, you need to compile and link it into your unit test
763 program. However, when the file contains a definition for the `main()`
764 function, it will clash with the `main()` of your unit test, and will result in
767 The right solution is to split it into three files:
768 1. `foo.h` which contains the declarations,
769 1. `foo.cc` which contains the definitions except `main()`, and
770 1. `foo_main.cc` which contains nothing but the definition of `main()`.
772 Then `foo.cc` can be easily tested.
774 If you are adding tests to an existing file and don't want an intrusive change
775 like this, there is a hack: just include the entire `foo.cc` file in your unit
778 // File foo_unittest.cc
780 // The headers section
783 // Renames main() in foo.cc to make room for the unit test main()
786 #include "a/b/foo.cc"
788 // The tests start here.
793 However, please remember this is a hack and should only be used as the last
796 ## What can the statement argument in ASSERT\_DEATH() be? ##
798 `ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used
799 wherever `_statement_` is valid. So basically `_statement_` can be any C++
800 statement that makes sense in the current context. In particular, it can
801 reference global and/or local variables, and can be:
802 * a simple function call (often the case),
803 * a complex expression, or
804 * a compound statement.
806 Some examples are shown here:
809 // A death test can be a simple function call.
810 TEST(MyDeathTest, FunctionCall) {
811 ASSERT_DEATH(Xyz(5), "Xyz failed");
814 // Or a complex expression that references variables and functions.
815 TEST(MyDeathTest, ComplexExpression) {
816 const bool c = Condition();
817 ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
818 "(Func1|Method) failed");
821 // Death assertions can be used any where in a function. In
822 // particular, they can be inside a loop.
823 TEST(MyDeathTest, InsideLoop) {
824 // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
825 for (int i = 0; i < 5; i++) {
826 EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
827 ::testing::Message() << "where i is " << i);
831 // A death assertion can contain a compound statement.
832 TEST(MyDeathTest, CompoundStatement) {
833 // Verifies that at lease one of Bar(0), Bar(1), ..., and
836 for (int i = 0; i < 5; i++) {
840 "Bar has \\d+ errors");}
843 `googletest_unittest.cc` contains more examples if you are interested.
845 ## What syntax does the regular expression in ASSERT\_DEATH use? ##
847 On POSIX systems, Google Test uses the POSIX Extended regular
849 (http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
850 On Windows, it uses a limited variant of regular expression
851 syntax. For more details, see the
852 [regular expression syntax](AdvancedGuide.md#Regular_Expression_Syntax).
854 ## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ##
856 Google Test needs to be able to create objects of your test fixture class, so
857 it must have a default constructor. Normally the compiler will define one for
858 you. However, there are cases where you have to define your own:
859 * 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.
860 * 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`.)
862 ## Why does ASSERT\_DEATH complain about previous threads that were already joined? ##
864 With the Linux pthread library, there is no turning back once you cross the
865 line from single thread to multiple threads. The first time you create a
866 thread, a manager thread is created in addition, so you get 3, not 2, threads.
867 Later when the thread you create joins the main thread, the thread count
868 decrements by 1, but the manager thread will never be killed, so you still have
869 2 threads, which means you cannot safely run a death test.
871 The new NPTL thread library doesn't suffer from this problem, as it doesn't
872 create a manager thread. However, if you don't control which machine your test
873 runs on, you shouldn't depend on this.
875 ## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ##
877 Google Test does not interleave tests from different test cases. That is, it
878 runs all tests in one test case first, and then runs all tests in the next test
879 case, and so on. Google Test does this because it needs to set up a test case
880 before the first test in it is run, and tear it down afterwords. Splitting up
881 the test case would require multiple set-up and tear-down processes, which is
882 inefficient and makes the semantics unclean.
884 If we were to determine the order of tests based on test name instead of test
885 case name, then we would have a problem with the following situation:
888 TEST_F(FooTest, AbcDeathTest) { ... }
889 TEST_F(FooTest, Uvw) { ... }
891 TEST_F(BarTest, DefDeathTest) { ... }
892 TEST_F(BarTest, Xyz) { ... }
895 Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
896 interleave tests from different test cases, we need to run all tests in the
897 `FooTest` case before running any test in the `BarTest` case. This contradicts
898 with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
900 ## 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? ##
902 You don't have to, but if you like, you may split up the test case into
903 `FooTest` and `FooDeathTest`, where the names make it clear that they are
907 class FooTest : public ::testing::Test { ... };
909 TEST_F(FooTest, Abc) { ... }
910 TEST_F(FooTest, Def) { ... }
912 typedef FooTest FooDeathTest;
914 TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
915 TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
918 ## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ##
920 If you use a user-defined type `FooType` in an assertion, you must make sure
921 there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
922 defined such that we can print a value of `FooType`.
924 In addition, if `FooType` is declared in a name space, the `<<` operator also
925 needs to be defined in the _same_ name space.
927 ## How do I suppress the memory leak messages on Windows? ##
929 Since the statically initialized Google Test singleton requires allocations on
930 the heap, the Visual C++ memory leak detector will report memory leaks at the
931 end of the program run. The easiest way to avoid this is to use the
932 `_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
933 statically initialized heap objects. See MSDN for more details and additional
934 heap check/debug routines.
936 ## 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! ##
938 You may get a number of the following linker error or warnings if you
939 attempt to link your test project with the Google Test library when
940 your project and the are not built using the same compiler settings.
942 * LNK2005: symbol already defined in object
943 * LNK4217: locally defined symbol 'symbol' imported in function 'function'
944 * LNK4049: locally defined symbol 'symbol' imported
946 The Google Test project (gtest.vcproj) has the Runtime Library option
947 set to /MT (use multi-threaded static libraries, /MTd for debug). If
948 your project uses something else, for example /MD (use multi-threaded
949 DLLs, /MDd for debug), you need to change the setting in the Google
950 Test project to match your project's.
952 To update this setting open the project properties in the Visual
953 Studio IDE then select the branch Configuration Properties | C/C++ |
954 Code Generation and change the option "Runtime Library". You may also try
955 using gtest-md.vcproj instead of gtest.vcproj.
957 ## I put my tests in a library and Google Test doesn't run them. What's happening? ##
959 [warning](Primer.md#important-note-for-visual-c-users) on
960 the Google Test Primer page?
962 ## I want to use Google Test with Visual Studio but don't know where to start. ##
963 Many people are in your position and one of the posted his solution to
966 ## I am seeing compile errors mentioning std::type\_traits when I try to use Google Test on Solaris. ##
967 Google Test uses parts of the standard C++ library that SunStudio does not support.
968 Our users reported success using alternative implementations. Try running the build after runing this commad:
970 `export CC=cc CXX=CC CXXFLAGS='-library=stlport4'`
972 ## How can my code detect if it is running in a test? ##
974 If you write code that sniffs whether it's running in a test and does
975 different things accordingly, you are leaking test-only logic into
976 production code and there is no easy way to ensure that the test-only
977 code paths aren't run by mistake in production. Such cleverness also
979 [Heisenbugs](http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug).
980 Therefore we strongly advise against the practice, and Google Test doesn't
981 provide a way to do it.
983 In general, the recommended way to cause the code to behave
984 differently under test is [dependency injection](http://jamesshore.com/Blog/Dependency-Injection-Demystified.html).
985 You can inject different functionality from the test and from the
986 production code. Since your production code doesn't link in the
987 for-test logic at all, there is no danger in accidentally running it.
989 However, if you _really_, _really_, _really_ have no choice, and if
990 you follow the rule of ending your test program names with `_test`,
991 you can use the _horrible_ hack of sniffing your executable name
992 (`argv[0]` in `main()`) to know whether the code is under test.
994 ## Google Test defines a macro that clashes with one defined by another library. How do I deal with that? ##
996 In C++, macros don't obey namespaces. Therefore two libraries that
997 both define a macro of the same name will clash if you `#include` both
998 definitions. In case a Google Test macro clashes with another
999 library, you can force Google Test to rename its macro to avoid the
1002 Specifically, if both Google Test and some other code define macro
1005 -DGTEST_DONT_DEFINE_FOO=1
1007 to the compiler flags to tell Google Test to change the macro's name
1008 from `FOO` to `GTEST_FOO`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
1010 GTEST_TEST(SomeTest, DoesThis) { ... }
1014 TEST(SomeTest, DoesThis) { ... }
1016 in order to define a test.
1018 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.
1021 ## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? ##
1025 The rule is **all test methods in the same test case must use the same fixture class**. This means that the following is **allowed** because both tests use the same fixture class (`::testing::Test`).
1029 TEST(CoolTest, DoSomething) {
1035 TEST(CoolTest, DoSomething) {
1041 However, the following code is **not allowed** and will produce a runtime error from Google Test because the test methods are using different test fixture classes with the same test case name.
1045 class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest
1046 TEST_F(CoolTest, DoSomething) {
1052 class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest
1053 TEST_F(CoolTest, DoSomething) {
1059 ## How do I build Google Testing Framework with Xcode 4? ##
1061 If you try to build Google Test's Xcode project with Xcode 4.0 or later, you may encounter an error message that looks like
1062 "Missing SDK in target gtest\_framework: /Developer/SDKs/MacOSX10.4u.sdk". That means that Xcode does not support the SDK the project is targeting. See the Xcode section in the [README](../README.md) file on how to resolve this.
1064 ## My question is not covered in your FAQ! ##
1066 If you cannot find the answer to your question in this FAQ, there are
1067 some other resources you can use:
1069 1. read other [wiki pages](../docs),
1070 1. search the mailing list [archive](https://groups.google.com/forum/#!forum/googletestframework),
1071 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.).
1073 Please note that creating an issue in the
1074 [issue tracker](https://github.com/google/googletest/issues) is _not_
1075 a good way to get your answer, as it is monitored infrequently by a
1076 very small number of people.
1078 When asking a question, it's helpful to provide as much of the
1079 following information as possible (people cannot help you if there's
1080 not enough information in your question):
1082 * the version (or the commit hash if you check out from Git 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),
1083 * your operating system,
1084 * the name and version of your compiler,
1085 * the complete command line flags you give to your compiler,
1086 * the complete compiler error messages (if the question is about compilation),
1087 * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.