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