1 2 3Now that you have read [Primer](V1_7_Primer.md) and learned how to write tests 4using Google Test, it's time to learn some new tricks. This document 5will show you more assertions as well as how to construct complex 6failure messages, propagate fatal failures, reuse and speed up your 7test fixtures, and use various flags with your tests. 8 9# More Assertions # 10 11This section covers some less frequently used, but still significant, 12assertions. 13 14## Explicit Success and Failure ## 15 16These three assertions do not actually test a value or expression. Instead, 17they generate a success or failure directly. Like the macros that actually 18perform a test, you may stream a custom failure message into the them. 19 20| `SUCCEED();` | 21|:-------------| 22 23Generates a success. This does NOT make the overall test succeed. A test is 24considered successful only if none of its assertions fail during its execution. 25 26Note: `SUCCEED()` is purely documentary and currently doesn't generate any 27user-visible output. However, we may add `SUCCEED()` messages to Google Test's 28output in the future. 29 30| `FAIL();` | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` | 31|:-----------|:-----------------|:------------------------------------------------------| 32 33`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal 34failure. These are useful when control flow, rather than a Boolean expression, 35deteremines the test's success or failure. For example, you might want to write 36something like: 37 38``` 39switch(expression) { 40 case 1: ... some checks ... 41 case 2: ... some other checks 42 ... 43 default: FAIL() << "We shouldn't get here."; 44} 45``` 46 47_Availability_: Linux, Windows, Mac. 48 49## Exception Assertions ## 50 51These are for verifying that a piece of code throws (or does not 52throw) an exception of the given type: 53 54| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | 55|:--------------------|:-----------------------|:-------------| 56| `ASSERT_THROW(`_statement_, _exception\_type_`);` | `EXPECT_THROW(`_statement_, _exception\_type_`);` | _statement_ throws an exception of the given type | 57| `ASSERT_ANY_THROW(`_statement_`);` | `EXPECT_ANY_THROW(`_statement_`);` | _statement_ throws an exception of any type | 58| `ASSERT_NO_THROW(`_statement_`);` | `EXPECT_NO_THROW(`_statement_`);` | _statement_ doesn't throw any exception | 59 60Examples: 61 62``` 63ASSERT_THROW(Foo(5), bar_exception); 64 65EXPECT_NO_THROW({ 66 int n = 5; 67 Bar(&n); 68}); 69``` 70 71_Availability_: Linux, Windows, Mac; since version 1.1.0. 72 73## Predicate Assertions for Better Error Messages ## 74 75Even though Google Test has a rich set of assertions, they can never be 76complete, as it's impossible (nor a good idea) to anticipate all the scenarios 77a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` 78to check a complex expression, for lack of a better macro. This has the problem 79of not showing you the values of the parts of the expression, making it hard to 80understand what went wrong. As a workaround, some users choose to construct the 81failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this 82is awkward especially when the expression has side-effects or is expensive to 83evaluate. 84 85Google Test gives you three different options to solve this problem: 86 87### Using an Existing Boolean Function ### 88 89If you already have a function or a functor that returns `bool` (or a type 90that can be implicitly converted to `bool`), you can use it in a _predicate 91assertion_ to get the function arguments printed for free: 92 93| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | 94|:--------------------|:-----------------------|:-------------| 95| `ASSERT_PRED1(`_pred1, val1_`);` | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true | 96| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` | _pred2(val1, val2)_ returns true | 97| ... | ... | ... | 98 99In the above, _predn_ is an _n_-ary predicate function or functor, where 100_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds 101if the predicate returns `true` when applied to the given arguments, and fails 102otherwise. When the assertion fails, it prints the value of each argument. In 103either case, the arguments are evaluated exactly once. 104 105Here's an example. Given 106 107``` 108// Returns true iff m and n have no common divisors except 1. 109bool MutuallyPrime(int m, int n) { ... } 110const int a = 3; 111const int b = 4; 112const int c = 10; 113``` 114 115the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the 116assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message 117 118<pre> 119!MutuallyPrime(b, c) is false, where<br> 120b is 4<br> 121c is 10<br> 122</pre> 123 124**Notes:** 125 126 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this](V1_7_FAQ.md#the-compiler-complains-about-undefined-references-to-some-static-const-member-variables-but-i-did-define-them-in-the-class-body-whats-wrong) for how to resolve it. 127 1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know. 128 129_Availability_: Linux, Windows, Mac 130 131### Using a Function That Returns an AssertionResult ### 132 133While `EXPECT_PRED*()` and friends are handy for a quick job, the 134syntax is not satisfactory: you have to use different macros for 135different arities, and it feels more like Lisp than C++. The 136`::testing::AssertionResult` class solves this problem. 137 138An `AssertionResult` object represents the result of an assertion 139(whether it's a success or a failure, and an associated message). You 140can create an `AssertionResult` using one of these factory 141functions: 142 143``` 144namespace testing { 145 146// Returns an AssertionResult object to indicate that an assertion has 147// succeeded. 148AssertionResult AssertionSuccess(); 149 150// Returns an AssertionResult object to indicate that an assertion has 151// failed. 152AssertionResult AssertionFailure(); 153 154} 155``` 156 157You can then use the `<<` operator to stream messages to the 158`AssertionResult` object. 159 160To provide more readable messages in Boolean assertions 161(e.g. `EXPECT_TRUE()`), write a predicate function that returns 162`AssertionResult` instead of `bool`. For example, if you define 163`IsEven()` as: 164 165``` 166::testing::AssertionResult IsEven(int n) { 167 if ((n % 2) == 0) 168 return ::testing::AssertionSuccess(); 169 else 170 return ::testing::AssertionFailure() << n << " is odd"; 171} 172``` 173 174instead of: 175 176``` 177bool IsEven(int n) { 178 return (n % 2) == 0; 179} 180``` 181 182the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: 183 184<pre> 185Value of: IsEven(Fib(4))<br> 186Actual: false (*3 is odd*)<br> 187Expected: true<br> 188</pre> 189 190instead of a more opaque 191 192<pre> 193Value of: IsEven(Fib(4))<br> 194Actual: false<br> 195Expected: true<br> 196</pre> 197 198If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` 199as well, and are fine with making the predicate slower in the success 200case, you can supply a success message: 201 202``` 203::testing::AssertionResult IsEven(int n) { 204 if ((n % 2) == 0) 205 return ::testing::AssertionSuccess() << n << " is even"; 206 else 207 return ::testing::AssertionFailure() << n << " is odd"; 208} 209``` 210 211Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print 212 213<pre> 214Value of: IsEven(Fib(6))<br> 215Actual: true (8 is even)<br> 216Expected: false<br> 217</pre> 218 219_Availability_: Linux, Windows, Mac; since version 1.4.1. 220 221### Using a Predicate-Formatter ### 222 223If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and 224`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your 225predicate do not support streaming to `ostream`, you can instead use the 226following _predicate-formatter assertions_ to _fully_ customize how the 227message is formatted: 228 229| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | 230|:--------------------|:-----------------------|:-------------| 231| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);` | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`); | _pred\_format1(val1)_ is successful | 232| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful | 233| `...` | `...` | `...` | 234 235The difference between this and the previous two groups of macros is that instead of 236a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_ 237(_pred\_formatn_), which is a function or functor with the signature: 238 239`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);` 240 241where _val1_, _val2_, ..., and _valn_ are the values of the predicate 242arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding 243expressions as they appear in the source code. The types `T1`, `T2`, ..., and 244`Tn` can be either value types or reference types. For example, if an 245argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`, 246whichever is appropriate. 247 248A predicate-formatter returns a `::testing::AssertionResult` object to indicate 249whether the assertion has succeeded or not. The only way to create such an 250object is to call one of these factory functions: 251 252As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`: 253 254``` 255// Returns the smallest prime common divisor of m and n, 256// or 1 when m and n are mutually prime. 257int SmallestPrimeCommonDivisor(int m, int n) { ... } 258 259// A predicate-formatter for asserting that two integers are mutually prime. 260::testing::AssertionResult AssertMutuallyPrime(const char* m_expr, 261 const char* n_expr, 262 int m, 263 int n) { 264 if (MutuallyPrime(m, n)) 265 return ::testing::AssertionSuccess(); 266 267 return ::testing::AssertionFailure() 268 << m_expr << " and " << n_expr << " (" << m << " and " << n 269 << ") are not mutually prime, " << "as they have a common divisor " 270 << SmallestPrimeCommonDivisor(m, n); 271} 272``` 273 274With this predicate-formatter, we can use 275 276``` 277EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); 278``` 279 280to generate the message 281 282<pre> 283b and c (4 and 10) are not mutually prime, as they have a common divisor 2.<br> 284</pre> 285 286As you may have realized, many of the assertions we introduced earlier are 287special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are 288indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`. 289 290_Availability_: Linux, Windows, Mac. 291 292 293## Floating-Point Comparison ## 294 295Comparing floating-point numbers is tricky. Due to round-off errors, it is 296very unlikely that two floating-points will match exactly. Therefore, 297`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points 298can have a wide value range, no single fixed error bound works. It's better to 299compare by a fixed relative error bound, except for values close to 0 due to 300the loss of precision there. 301 302In general, for floating-point comparison to make sense, the user needs to 303carefully choose the error bound. If they don't want or care to, comparing in 304terms of Units in the Last Place (ULPs) is a good default, and Google Test 305provides assertions to do this. Full details about ULPs are quite long; if you 306want to learn more, see 307[this article on float comparison](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm). 308 309### Floating-Point Macros ### 310 311| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | 312|:--------------------|:-----------------------|:-------------| 313| `ASSERT_FLOAT_EQ(`_expected, actual_`);` | `EXPECT_FLOAT_EQ(`_expected, actual_`);` | the two `float` values are almost equal | 314| `ASSERT_DOUBLE_EQ(`_expected, actual_`);` | `EXPECT_DOUBLE_EQ(`_expected, actual_`);` | the two `double` values are almost equal | 315 316By "almost equal", we mean the two values are within 4 ULP's from each 317other. 318 319The following assertions allow you to choose the acceptable error bound: 320 321| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | 322|:--------------------|:-----------------------|:-------------| 323| `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error | 324 325_Availability_: Linux, Windows, Mac. 326 327### Floating-Point Predicate-Format Functions ### 328 329Some floating-point operations are useful, but not that often used. In order 330to avoid an explosion of new macros, we provide them as predicate-format 331functions that can be used in predicate assertion macros (e.g. 332`EXPECT_PRED_FORMAT2`, etc). 333 334``` 335EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2); 336EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2); 337``` 338 339Verifies that _val1_ is less than, or almost equal to, _val2_. You can 340replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`. 341 342_Availability_: Linux, Windows, Mac. 343 344## Windows HRESULT assertions ## 345 346These assertions test for `HRESULT` success or failure. 347 348| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | 349|:--------------------|:-----------------------|:-------------| 350| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` | 351| `ASSERT_HRESULT_FAILED(`_expression_`);` | `EXPECT_HRESULT_FAILED(`_expression_`);` | _expression_ is a failure `HRESULT` | 352 353The generated output contains the human-readable error message 354associated with the `HRESULT` code returned by _expression_. 355 356You might use them like this: 357 358``` 359CComPtr shell; 360ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); 361CComVariant empty; 362ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); 363``` 364 365_Availability_: Windows. 366 367## Type Assertions ## 368 369You can call the function 370``` 371::testing::StaticAssertTypeEq<T1, T2>(); 372``` 373to assert that types `T1` and `T2` are the same. The function does 374nothing if the assertion is satisfied. If the types are different, 375the function call will fail to compile, and the compiler error message 376will likely (depending on the compiler) show you the actual values of 377`T1` and `T2`. This is mainly useful inside template code. 378 379_Caveat:_ When used inside a member function of a class template or a 380function template, `StaticAssertTypeEq<T1, T2>()` is effective _only if_ 381the function is instantiated. For example, given: 382``` 383template <typename T> class Foo { 384 public: 385 void Bar() { ::testing::StaticAssertTypeEq<int, T>(); } 386}; 387``` 388the code: 389``` 390void Test1() { Foo<bool> foo; } 391``` 392will _not_ generate a compiler error, as `Foo<bool>::Bar()` is never 393actually instantiated. Instead, you need: 394``` 395void Test2() { Foo<bool> foo; foo.Bar(); } 396``` 397to cause a compiler error. 398 399_Availability:_ Linux, Windows, Mac; since version 1.3.0. 400 401## Assertion Placement ## 402 403You can use assertions in any C++ function. In particular, it doesn't 404have to be a method of the test fixture class. The one constraint is 405that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`) 406can only be used in void-returning functions. This is a consequence of 407Google Test not using exceptions. By placing it in a non-void function 408you'll get a confusing compile error like 409`"error: void value not ignored as it ought to be"`. 410 411If you need to use assertions in a function that returns non-void, one option 412is to make the function return the value in an out parameter instead. For 413example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You 414need to make sure that `*result` contains some sensible value even when the 415function returns prematurely. As the function now returns `void`, you can use 416any assertion inside of it. 417 418If changing the function's type is not an option, you should just use 419assertions that generate non-fatal failures, such as `ADD_FAILURE*` and 420`EXPECT_*`. 421 422_Note_: Constructors and destructors are not considered void-returning 423functions, according to the C++ language specification, and so you may not use 424fatal assertions in them. You'll get a compilation error if you try. A simple 425workaround is to transfer the entire body of the constructor or destructor to a 426private void-returning method. However, you should be aware that a fatal 427assertion failure in a constructor does not terminate the current test, as your 428intuition might suggest; it merely returns from the constructor early, possibly 429leaving your object in a partially-constructed state. Likewise, a fatal 430assertion failure in a destructor may leave your object in a 431partially-destructed state. Use assertions carefully in these situations! 432 433# Teaching Google Test How to Print Your Values # 434 435When a test assertion such as `EXPECT_EQ` fails, Google Test prints the 436argument values to help you debug. It does this using a 437user-extensible value printer. 438 439This printer knows how to print built-in C++ types, native arrays, STL 440containers, and any type that supports the `<<` operator. For other 441types, it prints the raw bytes in the value and hopes that you the 442user can figure it out. 443 444As mentioned earlier, the printer is _extensible_. That means 445you can teach it to do a better job at printing your particular type 446than to dump the bytes. To do that, define `<<` for your type: 447 448``` 449#include <iostream> 450 451namespace foo { 452 453class Bar { ... }; // We want Google Test to be able to print instances of this. 454 455// It's important that the << operator is defined in the SAME 456// namespace that defines Bar. C++'s look-up rules rely on that. 457::std::ostream& operator<<(::std::ostream& os, const Bar& bar) { 458 return os << bar.DebugString(); // whatever needed to print bar to os 459} 460 461} // namespace foo 462``` 463 464Sometimes, this might not be an option: your team may consider it bad 465style to have a `<<` operator for `Bar`, or `Bar` may already have a 466`<<` operator that doesn't do what you want (and you cannot change 467it). If so, you can instead define a `PrintTo()` function like this: 468 469``` 470#include <iostream> 471 472namespace foo { 473 474class Bar { ... }; 475 476// It's important that PrintTo() is defined in the SAME 477// namespace that defines Bar. C++'s look-up rules rely on that. 478void PrintTo(const Bar& bar, ::std::ostream* os) { 479 *os << bar.DebugString(); // whatever needed to print bar to os 480} 481 482} // namespace foo 483``` 484 485If you have defined both `<<` and `PrintTo()`, the latter will be used 486when Google Test is concerned. This allows you to customize how the value 487appears in Google Test's output without affecting code that relies on the 488behavior of its `<<` operator. 489 490If you want to print a value `x` using Google Test's value printer 491yourself, just call `::testing::PrintToString(`_x_`)`, which 492returns an `std::string`: 493 494``` 495vector<pair<Bar, int> > bar_ints = GetBarIntVector(); 496 497EXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) 498 << "bar_ints = " << ::testing::PrintToString(bar_ints); 499``` 500 501# Death Tests # 502 503In many applications, there are assertions that can cause application failure 504if a condition is not met. These sanity checks, which ensure that the program 505is in a known good state, are there to fail at the earliest possible time after 506some program state is corrupted. If the assertion checks the wrong condition, 507then the program may proceed in an erroneous state, which could lead to memory 508corruption, security holes, or worse. Hence it is vitally important to test 509that such assertion statements work as expected. 510 511Since these precondition checks cause the processes to die, we call such tests 512_death tests_. More generally, any test that checks that a program terminates 513(except by throwing an exception) in an expected fashion is also a death test. 514 515Note that if a piece of code throws an exception, we don't consider it "death" 516for the purpose of death tests, as the caller of the code could catch the exception 517and avoid the crash. If you want to verify exceptions thrown by your code, 518see [Exception Assertions](#exception-assertions). 519 520If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#catching-failures). 521 522## How to Write a Death Test ## 523 524Google Test has the following macros to support death tests: 525 526| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | 527|:--------------------|:-----------------------|:-------------| 528| `ASSERT_DEATH(`_statement, regex_`); | `EXPECT_DEATH(`_statement, regex_`); | _statement_ crashes with the given error | 529| `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`); | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`); | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing | 530| `ASSERT_EXIT(`_statement, predicate, regex_`); | `EXPECT_EXIT(`_statement, predicate, regex_`); |_statement_ exits with the given error and its exit code matches _predicate_ | 531 532where _statement_ is a statement that is expected to cause the process to 533die, _predicate_ is a function or function object that evaluates an integer 534exit status, and _regex_ is a regular expression that the stderr output of 535_statement_ is expected to match. Note that _statement_ can be _any valid 536statement_ (including _compound statement_) and doesn't have to be an 537expression. 538 539As usual, the `ASSERT` variants abort the current test function, while the 540`EXPECT` variants do not. 541 542**Note:** We use the word "crash" here to mean that the process 543terminates with a _non-zero_ exit status code. There are two 544possibilities: either the process has called `exit()` or `_exit()` 545with a non-zero value, or it may be killed by a signal. 546 547This means that if _statement_ terminates the process with a 0 exit 548code, it is _not_ considered a crash by `EXPECT_DEATH`. Use 549`EXPECT_EXIT` instead if this is the case, or if you want to restrict 550the exit code more precisely. 551 552A predicate here must accept an `int` and return a `bool`. The death test 553succeeds only if the predicate returns `true`. Google Test defines a few 554predicates that handle the most common cases: 555 556``` 557::testing::ExitedWithCode(exit_code) 558``` 559 560This expression is `true` if the program exited normally with the given exit 561code. 562 563``` 564::testing::KilledBySignal(signal_number) // Not available on Windows. 565``` 566 567This expression is `true` if the program was killed by the given signal. 568 569The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate 570that verifies the process' exit code is non-zero. 571 572Note that a death test only cares about three things: 573 574 1. does _statement_ abort or exit the process? 575 1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero? And 576 1. does the stderr output match _regex_? 577 578In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process. 579 580To write a death test, simply use one of the above macros inside your test 581function. For example, 582 583``` 584TEST(MyDeathTest, Foo) { 585 // This death test uses a compound statement. 586 ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()"); 587} 588TEST(MyDeathTest, NormalExit) { 589 EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success"); 590} 591TEST(MyDeathTest, KillMyself) { 592 EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal"); 593} 594``` 595 596verifies that: 597 598 * calling `Foo(5)` causes the process to die with the given error message, 599 * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and 600 * calling `KillMyself()` kills the process with signal `SIGKILL`. 601 602The test function body may contain other assertions and statements as well, if 603necessary. 604 605_Important:_ We strongly recommend you to follow the convention of naming your 606test case (not test) `*DeathTest` when it contains a death test, as 607demonstrated in the above example. The `Death Tests And Threads` section below 608explains why. 609 610If a test fixture class is shared by normal tests and death tests, you 611can use typedef to introduce an alias for the fixture class and avoid 612duplicating its code: 613``` 614class FooTest : public ::testing::Test { ... }; 615 616typedef FooTest FooDeathTest; 617 618TEST_F(FooTest, DoesThis) { 619 // normal test 620} 621 622TEST_F(FooDeathTest, DoesThat) { 623 // death test 624} 625``` 626 627_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0). `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0. 628 629## Regular Expression Syntax ## 630 631On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the 632[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) 633syntax in death tests. To learn about this syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). 634 635On Windows, Google Test uses its own simple regular expression 636implementation. It lacks many features you can find in POSIX extended 637regular expressions. For example, we don't support union (`"x|y"`), 638grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count 639(`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a 640literal character, period (`.`), or a single `\\` escape sequence; `x` 641and `y` denote regular expressions.): 642 643| `c` | matches any literal character `c` | 644|:----|:----------------------------------| 645| `\\d` | matches any decimal digit | 646| `\\D` | matches any character that's not a decimal digit | 647| `\\f` | matches `\f` | 648| `\\n` | matches `\n` | 649| `\\r` | matches `\r` | 650| `\\s` | matches any ASCII whitespace, including `\n` | 651| `\\S` | matches any character that's not a whitespace | 652| `\\t` | matches `\t` | 653| `\\v` | matches `\v` | 654| `\\w` | matches any letter, `_`, or decimal digit | 655| `\\W` | matches any character that `\\w` doesn't match | 656| `\\c` | matches any literal character `c`, which must be a punctuation | 657| `\\.` | matches the `.` character | 658| `.` | matches any single character except `\n` | 659| `A?` | matches 0 or 1 occurrences of `A` | 660| `A*` | matches 0 or many occurrences of `A` | 661| `A+` | matches 1 or many occurrences of `A` | 662| `^` | matches the beginning of a string (not that of each line) | 663| `$` | matches the end of a string (not that of each line) | 664| `xy` | matches `x` followed by `y` | 665 666To help you determine which capability is available on your system, 667Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX 668extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses 669the simple version. If you want your death tests to work in both 670cases, you can either `#if` on these macros or use the more limited 671syntax only. 672 673## How It Works ## 674 675Under the hood, `ASSERT_EXIT()` spawns a new process and executes the 676death test statement in that process. The details of of how precisely 677that happens depend on the platform and the variable 678`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the 679command-line flag `--gtest_death_test_style`). 680 681 * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which: 682 * If the variable's value is `"fast"`, the death test statement is immediately executed. 683 * If the variable's value is `"threadsafe"`, the child process re-executes the unit test binary just as it was originally invoked, but with some extra flags to cause just the single death test under consideration to be run. 684 * On Windows, the child is spawned using the `CreateProcess()` API, and re-executes the binary to cause just the single death test under consideration to be run - much like the `threadsafe` mode on POSIX. 685 686Other values for the variable are illegal and will cause the death test to 687fail. Currently, the flag's default value is `"fast"`. However, we reserve the 688right to change it in the future. Therefore, your tests should not depend on 689this. 690 691In either case, the parent process waits for the child process to complete, and checks that 692 693 1. the child's exit status satisfies the predicate, and 694 1. the child's stderr matches the regular expression. 695 696If the death test statement runs to completion without dying, the child 697process will nonetheless terminate, and the assertion fails. 698 699## Death Tests And Threads ## 700 701The reason for the two death test styles has to do with thread safety. Due to 702well-known problems with forking in the presence of threads, death tests should 703be run in a single-threaded context. Sometimes, however, it isn't feasible to 704arrange that kind of environment. For example, statically-initialized modules 705may start threads before main is ever reached. Once threads have been created, 706it may be difficult or impossible to clean them up. 707 708Google Test has three features intended to raise awareness of threading issues. 709 710 1. A warning is emitted if multiple threads are running when a death test is encountered. 711 1. Test cases with a name ending in "DeathTest" are run before all other tests. 712 1. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads. 713 714It's perfectly fine to create threads inside a death test statement; they are 715executed in a separate process and cannot affect the parent. 716 717## Death Test Styles ## 718 719The "threadsafe" death test style was introduced in order to help mitigate the 720risks of testing in a possibly multithreaded environment. It trades increased 721test execution time (potentially dramatically so) for improved thread safety. 722We suggest using the faster, default "fast" style unless your test has specific 723problems with it. 724 725You can choose a particular style of death tests by setting the flag 726programmatically: 727 728``` 729::testing::FLAGS_gtest_death_test_style = "threadsafe"; 730``` 731 732You can do this in `main()` to set the style for all death tests in the 733binary, or in individual tests. Recall that flags are saved before running each 734test and restored afterwards, so you need not do that yourself. For example: 735 736``` 737TEST(MyDeathTest, TestOne) { 738 ::testing::FLAGS_gtest_death_test_style = "threadsafe"; 739 // This test is run in the "threadsafe" style: 740 ASSERT_DEATH(ThisShouldDie(), ""); 741} 742 743TEST(MyDeathTest, TestTwo) { 744 // This test is run in the "fast" style: 745 ASSERT_DEATH(ThisShouldDie(), ""); 746} 747 748int main(int argc, char** argv) { 749 ::testing::InitGoogleTest(&argc, argv); 750 ::testing::FLAGS_gtest_death_test_style = "fast"; 751 return RUN_ALL_TESTS(); 752} 753``` 754 755## Caveats ## 756 757The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement. 758If it leaves the current function via a `return` statement or by throwing an exception, 759the death test is considered to have failed. Some Google Test macros may return 760from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_. 761 762Since _statement_ runs in the child process, any in-memory side effect (e.g. 763modifying a variable, releasing memory, etc) it causes will _not_ be observable 764in the parent process. In particular, if you release memory in a death test, 765your program will fail the heap check as the parent process will never see the 766memory reclaimed. To solve this problem, you can 767 768 1. try not to free memory in a death test; 769 1. free the memory again in the parent process; or 770 1. do not use the heap checker in your program. 771 772Due to an implementation detail, you cannot place multiple death test 773assertions on the same line; otherwise, compilation will fail with an unobvious 774error message. 775 776Despite the improved thread safety afforded by the "threadsafe" style of death 777test, thread problems such as deadlock are still possible in the presence of 778handlers registered with `pthread_atfork(3)`. 779 780# Using Assertions in Sub-routines # 781 782## Adding Traces to Assertions ## 783 784If a test sub-routine is called from several places, when an assertion 785inside it fails, it can be hard to tell which invocation of the 786sub-routine the failure is from. You can alleviate this problem using 787extra logging or custom failure messages, but that usually clutters up 788your tests. A better solution is to use the `SCOPED_TRACE` macro: 789 790| `SCOPED_TRACE(`_message_`);` | 791|:-----------------------------| 792 793where _message_ can be anything streamable to `std::ostream`. This 794macro will cause the current file name, line number, and the given 795message to be added in every failure message. The effect will be 796undone when the control leaves the current lexical scope. 797 798For example, 799 800``` 80110: void Sub1(int n) { 80211: EXPECT_EQ(1, Bar(n)); 80312: EXPECT_EQ(2, Bar(n + 1)); 80413: } 80514: 80615: TEST(FooTest, Bar) { 80716: { 80817: SCOPED_TRACE("A"); // This trace point will be included in 80918: // every failure in this scope. 81019: Sub1(1); 81120: } 81221: // Now it won't. 81322: Sub1(9); 81423: } 815``` 816 817could result in messages like these: 818 819``` 820path/to/foo_test.cc:11: Failure 821Value of: Bar(n) 822Expected: 1 823 Actual: 2 824 Trace: 825path/to/foo_test.cc:17: A 826 827path/to/foo_test.cc:12: Failure 828Value of: Bar(n + 1) 829Expected: 2 830 Actual: 3 831``` 832 833Without the trace, it would've been difficult to know which invocation 834of `Sub1()` the two failures come from respectively. (You could add an 835extra message to each assertion in `Sub1()` to indicate the value of 836`n`, but that's tedious.) 837 838Some tips on using `SCOPED_TRACE`: 839 840 1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the beginning of a sub-routine, instead of at each call site. 841 1. When calling sub-routines inside a loop, make the loop iterator part of the message in `SCOPED_TRACE` such that you can know which iteration the failure is from. 842 1. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for `SCOPED_TRACE`. You can simply use `""`. 843 1. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered. 844 1. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file! 845 846_Availability:_ Linux, Windows, Mac. 847 848## Propagating Fatal Failures ## 849 850A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that 851when they fail they only abort the _current function_, not the entire test. For 852example, the following test will segfault: 853``` 854void Subroutine() { 855 // Generates a fatal failure and aborts the current function. 856 ASSERT_EQ(1, 2); 857 // The following won't be executed. 858 ... 859} 860 861TEST(FooTest, Bar) { 862 Subroutine(); 863 // The intended behavior is for the fatal failure 864 // in Subroutine() to abort the entire test. 865 // The actual behavior: the function goes on after Subroutine() returns. 866 int* p = NULL; 867 *p = 3; // Segfault! 868} 869``` 870 871Since we don't use exceptions, it is technically impossible to 872implement the intended behavior here. To alleviate this, Google Test 873provides two solutions. You could use either the 874`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the 875`HasFatalFailure()` function. They are described in the following two 876subsections. 877 878### Asserting on Subroutines ### 879 880As shown above, if your test calls a subroutine that has an `ASSERT_*` 881failure in it, the test will continue after the subroutine 882returns. This may not be what you want. 883 884Often people want fatal failures to propagate like exceptions. For 885that Google Test offers the following macros: 886 887| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | 888|:--------------------|:-----------------------|:-------------| 889| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. | 890 891Only failures in the thread that executes the assertion are checked to 892determine the result of this type of assertions. If _statement_ 893creates new threads, failures in these threads are ignored. 894 895Examples: 896 897``` 898ASSERT_NO_FATAL_FAILURE(Foo()); 899 900int i; 901EXPECT_NO_FATAL_FAILURE({ 902 i = Bar(); 903}); 904``` 905 906_Availability:_ Linux, Windows, Mac. Assertions from multiple threads 907are currently not supported. 908 909### Checking for Failures in the Current Test ### 910 911`HasFatalFailure()` in the `::testing::Test` class returns `true` if an 912assertion in the current test has suffered a fatal failure. This 913allows functions to catch fatal failures in a sub-routine and return 914early. 915 916``` 917class Test { 918 public: 919 ... 920 static bool HasFatalFailure(); 921}; 922``` 923 924The typical usage, which basically simulates the behavior of a thrown 925exception, is: 926 927``` 928TEST(FooTest, Bar) { 929 Subroutine(); 930 // Aborts if Subroutine() had a fatal failure. 931 if (HasFatalFailure()) 932 return; 933 // The following won't be executed. 934 ... 935} 936``` 937 938If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test 939fixture, you must add the `::testing::Test::` prefix, as in: 940 941``` 942if (::testing::Test::HasFatalFailure()) 943 return; 944``` 945 946Similarly, `HasNonfatalFailure()` returns `true` if the current test 947has at least one non-fatal failure, and `HasFailure()` returns `true` 948if the current test has at least one failure of either kind. 949 950_Availability:_ Linux, Windows, Mac. `HasNonfatalFailure()` and 951`HasFailure()` are available since version 1.4.0. 952 953# Logging Additional Information # 954 955In your test code, you can call `RecordProperty("key", value)` to log 956additional information, where `value` can be either a string or an `int`. The _last_ value recorded for a key will be emitted to the XML output 957if you specify one. For example, the test 958 959``` 960TEST_F(WidgetUsageTest, MinAndMaxWidgets) { 961 RecordProperty("MaximumWidgets", ComputeMaxUsage()); 962 RecordProperty("MinimumWidgets", ComputeMinUsage()); 963} 964``` 965 966will output XML like this: 967 968``` 969... 970 <testcase name="MinAndMaxWidgets" status="run" time="6" classname="WidgetUsageTest" 971 MaximumWidgets="12" 972 MinimumWidgets="9" /> 973... 974``` 975 976_Note_: 977 * `RecordProperty()` is a static member of the `Test` class. Therefore it needs to be prefixed with `::testing::Test::` if used outside of the `TEST` body and the test fixture class. 978 * `key` must be a valid XML attribute name, and cannot conflict with the ones already used by Google Test (`name`, `status`, `time`, `classname`, `type_param`, and `value_param`). 979 * Calling `RecordProperty()` outside of the lifespan of a test is allowed. If it's called outside of a test but between a test case's `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed to the XML element for the test case. If it's called outside of all test cases (e.g. in a test environment), it will be attributed to the top-level XML element. 980 981_Availability_: Linux, Windows, Mac. 982 983# Sharing Resources Between Tests in the Same Test Case # 984 985 986 987Google Test creates a new test fixture object for each test in order to make 988tests independent and easier to debug. However, sometimes tests use resources 989that are expensive to set up, making the one-copy-per-test model prohibitively 990expensive. 991 992If the tests don't change the resource, there's no harm in them sharing a 993single resource copy. So, in addition to per-test set-up/tear-down, Google Test 994also supports per-test-case set-up/tear-down. To use it: 995 996 1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources. 997 1. In the same test fixture class, define a `static void SetUpTestCase()` function (remember not to spell it as **`SetupTestCase`** with a small `u`!) to set up the shared resources and a `static void TearDownTestCase()` function to tear them down. 998 999That's it! Google Test automatically calls `SetUpTestCase()` before running the 1000_first test_ in the `FooTest` test case (i.e. before creating the first 1001`FooTest` object), and calls `TearDownTestCase()` after running the _last test_ 1002in it (i.e. after deleting the last `FooTest` object). In between, the tests 1003can use the shared resources. 1004 1005Remember that the test order is undefined, so your code can't depend on a test 1006preceding or following another. Also, the tests must either not modify the 1007state of any shared resource, or, if they do modify the state, they must 1008restore the state to its original value before passing control to the next 1009test. 1010 1011Here's an example of per-test-case set-up and tear-down: 1012``` 1013class FooTest : public ::testing::Test { 1014 protected: 1015 // Per-test-case set-up. 1016 // Called before the first test in this test case. 1017 // Can be omitted if not needed. 1018 static void SetUpTestCase() { 1019 shared_resource_ = new ...; 1020 } 1021 1022 // Per-test-case tear-down. 1023 // Called after the last test in this test case. 1024 // Can be omitted if not needed. 1025 static void TearDownTestCase() { 1026 delete shared_resource_; 1027 shared_resource_ = NULL; 1028 } 1029 1030 // You can define per-test set-up and tear-down logic as usual. 1031 virtual void SetUp() { ... } 1032 virtual void TearDown() { ... } 1033 1034 // Some expensive resource shared by all tests. 1035 static T* shared_resource_; 1036}; 1037 1038T* FooTest::shared_resource_ = NULL; 1039 1040TEST_F(FooTest, Test1) { 1041 ... you can refer to shared_resource here ... 1042} 1043TEST_F(FooTest, Test2) { 1044 ... you can refer to shared_resource here ... 1045} 1046``` 1047 1048_Availability:_ Linux, Windows, Mac. 1049 1050# Global Set-Up and Tear-Down # 1051 1052Just as you can do set-up and tear-down at the test level and the test case 1053level, you can also do it at the test program level. Here's how. 1054 1055First, you subclass the `::testing::Environment` class to define a test 1056environment, which knows how to set-up and tear-down: 1057 1058``` 1059class Environment { 1060 public: 1061 virtual ~Environment() {} 1062 // Override this to define how to set up the environment. 1063 virtual void SetUp() {} 1064 // Override this to define how to tear down the environment. 1065 virtual void TearDown() {} 1066}; 1067``` 1068 1069Then, you register an instance of your environment class with Google Test by 1070calling the `::testing::AddGlobalTestEnvironment()` function: 1071 1072``` 1073Environment* AddGlobalTestEnvironment(Environment* env); 1074``` 1075 1076Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of 1077the environment object, then runs the tests if there was no fatal failures, and 1078finally calls `TearDown()` of the environment object. 1079 1080It's OK to register multiple environment objects. In this case, their `SetUp()` 1081will be called in the order they are registered, and their `TearDown()` will be 1082called in the reverse order. 1083 1084Note that Google Test takes ownership of the registered environment objects. 1085Therefore **do not delete them** by yourself. 1086 1087You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is 1088called, probably in `main()`. If you use `gtest_main`, you need to call 1089this before `main()` starts for it to take effect. One way to do this is to 1090define a global variable like this: 1091 1092``` 1093::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment); 1094``` 1095 1096However, we strongly recommend you to write your own `main()` and call 1097`AddGlobalTestEnvironment()` there, as relying on initialization of global 1098variables makes the code harder to read and may cause problems when you 1099register multiple environments from different translation units and the 1100environments have dependencies among them (remember that the compiler doesn't 1101guarantee the order in which global variables from different translation units 1102are initialized). 1103 1104_Availability:_ Linux, Windows, Mac. 1105 1106 1107# Value Parameterized Tests # 1108 1109_Value-parameterized tests_ allow you to test your code with different 1110parameters without writing multiple copies of the same test. 1111 1112Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag. 1113 1114``` 1115TEST(MyCodeTest, TestFoo) { 1116 // A code to test foo(). 1117} 1118``` 1119 1120Usually people factor their test code into a function with a Boolean parameter in such situations. The function sets the flag, then executes the testing code. 1121 1122``` 1123void TestFooHelper(bool flag_value) { 1124 flag = flag_value; 1125 // A code to test foo(). 1126} 1127 1128TEST(MyCodeTest, TestFoo) { 1129 TestFooHelper(false); 1130 TestFooHelper(true); 1131} 1132``` 1133 1134But this setup has serious drawbacks. First, when a test assertion fails in your tests, it becomes unclear what value of the parameter caused it to fail. You can stream a clarifying message into your `EXPECT`/`ASSERT` statements, but it you'll have to do it with all of them. Second, you have to add one such helper function per test. What if you have ten tests? Twenty? A hundred? 1135 1136Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values. 1137 1138Here are some other situations when value-parameterized tests come handy: 1139 1140 * You want to test different implementations of an OO interface. 1141 * You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it! 1142 1143## How to Write Value-Parameterized Tests ## 1144 1145To write value-parameterized tests, first you should define a fixture 1146class. It must be derived from both `::testing::Test` and 1147`::testing::WithParamInterface<T>` (the latter is a pure interface), 1148where `T` is the type of your parameter values. For convenience, you 1149can just derive the fixture class from `::testing::TestWithParam<T>`, 1150which itself is derived from both `::testing::Test` and 1151`::testing::WithParamInterface<T>`. `T` can be any copyable type. If 1152it's a raw pointer, you are responsible for managing the lifespan of 1153the pointed values. 1154 1155``` 1156class FooTest : public ::testing::TestWithParam<const char*> { 1157 // You can implement all the usual fixture class members here. 1158 // To access the test parameter, call GetParam() from class 1159 // TestWithParam<T>. 1160}; 1161 1162// Or, when you want to add parameters to a pre-existing fixture class: 1163class BaseTest : public ::testing::Test { 1164 ... 1165}; 1166class BarTest : public BaseTest, 1167 public ::testing::WithParamInterface<const char*> { 1168 ... 1169}; 1170``` 1171 1172Then, use the `TEST_P` macro to define as many test patterns using 1173this fixture as you want. The `_P` suffix is for "parameterized" or 1174"pattern", whichever you prefer to think. 1175 1176``` 1177TEST_P(FooTest, DoesBlah) { 1178 // Inside a test, access the test parameter with the GetParam() method 1179 // of the TestWithParam<T> class: 1180 EXPECT_TRUE(foo.Blah(GetParam())); 1181 ... 1182} 1183 1184TEST_P(FooTest, HasBlahBlah) { 1185 ... 1186} 1187``` 1188 1189Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test 1190case with any set of parameters you want. Google Test defines a number of 1191functions for generating test parameters. They return what we call 1192(surprise!) _parameter generators_. Here is a summary of them, 1193which are all in the `testing` namespace: 1194 1195| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | 1196|:----------------------------|:------------------------------------------------------------------------------------------------------------------| 1197| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | 1198| `ValuesIn(container)` and `ValuesIn(begin, end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. `container`, `begin`, and `end` can be expressions whose values are determined at run time. | 1199| `Bool()` | Yields sequence `{false, true}`. | 1200| `Combine(g1, g2, ..., gN)` | Yields all combinations (the Cartesian product for the math savvy) of the values generated by the `N` generators. This is only available if your system provides the `<tr1/tuple>` header. If you are sure your system does, and Google Test disagrees, you can override it by defining `GTEST_HAS_TR1_TUPLE=1`. See comments in [include/gtest/internal/gtest-port.h](../include/gtest/internal/gtest-port.h) for more information. | 1201 1202For more details, see the comments at the definitions of these functions in the [source code](../include/gtest/gtest-param-test.h). 1203 1204The following statement will instantiate tests from the `FooTest` test case 1205each with parameter values `"meeny"`, `"miny"`, and `"moe"`. 1206 1207``` 1208INSTANTIATE_TEST_CASE_P(InstantiationName, 1209 FooTest, 1210 ::testing::Values("meeny", "miny", "moe")); 1211``` 1212 1213To distinguish different instances of the pattern (yes, you can 1214instantiate it more than once), the first argument to 1215`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual 1216test case name. Remember to pick unique prefixes for different 1217instantiations. The tests from the instantiation above will have these 1218names: 1219 1220 * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"` 1221 * `InstantiationName/FooTest.DoesBlah/1` for `"miny"` 1222 * `InstantiationName/FooTest.DoesBlah/2` for `"moe"` 1223 * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"` 1224 * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"` 1225 * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"` 1226 1227You can use these names in [--gtest\_filter](#running-a-subset-of-the-tests). 1228 1229This statement will instantiate all tests from `FooTest` again, each 1230with parameter values `"cat"` and `"dog"`: 1231 1232``` 1233const char* pets[] = {"cat", "dog"}; 1234INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, 1235 ::testing::ValuesIn(pets)); 1236``` 1237 1238The tests from the instantiation above will have these names: 1239 1240 * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"` 1241 * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"` 1242 * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"` 1243 * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"` 1244 1245Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_ 1246tests in the given test case, whether their definitions come before or 1247_after_ the `INSTANTIATE_TEST_CASE_P` statement. 1248 1249You can see 1250[these](../samples/sample7_unittest.cc) 1251[files](../samples/sample8_unittest.cc) for more examples. 1252 1253_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0. 1254 1255## Creating Value-Parameterized Abstract Tests ## 1256 1257In the above, we define and instantiate `FooTest` in the same source 1258file. Sometimes you may want to define value-parameterized tests in a 1259library and let other people instantiate them later. This pattern is 1260known as <i>abstract tests</i>. As an example of its application, when you 1261are designing an interface you can write a standard suite of abstract 1262tests (perhaps using a factory function as the test parameter) that 1263all implementations of the interface are expected to pass. When 1264someone implements the interface, he can instantiate your suite to get 1265all the interface-conformance tests for free. 1266 1267To define abstract tests, you should organize your code like this: 1268 1269 1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) in a header file, say `foo_param_test.h`. Think of this as _declaring_ your abstract tests. 1270 1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes `foo_param_test.h`. Think of this as _implementing_ your abstract tests. 1271 1272Once they are defined, you can instantiate them by including 1273`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking 1274with `foo_param_test.cc`. You can instantiate the same abstract test 1275case multiple times, possibly in different source files. 1276 1277# Typed Tests # 1278 1279Suppose you have multiple implementations of the same interface and 1280want to make sure that all of them satisfy some common requirements. 1281Or, you may have defined several types that are supposed to conform to 1282the same "concept" and you want to verify it. In both cases, you want 1283the same test logic repeated for different types. 1284 1285While you can write one `TEST` or `TEST_F` for each type you want to 1286test (and you may even factor the test logic into a function template 1287that you invoke from the `TEST`), it's tedious and doesn't scale: 1288if you want _m_ tests over _n_ types, you'll end up writing _m\*n_ 1289`TEST`s. 1290 1291_Typed tests_ allow you to repeat the same test logic over a list of 1292types. You only need to write the test logic once, although you must 1293know the type list when writing typed tests. Here's how you do it: 1294 1295First, define a fixture class template. It should be parameterized 1296by a type. Remember to derive it from `::testing::Test`: 1297 1298``` 1299template <typename T> 1300class FooTest : public ::testing::Test { 1301 public: 1302 ... 1303 typedef std::list<T> List; 1304 static T shared_; 1305 T value_; 1306}; 1307``` 1308 1309Next, associate a list of types with the test case, which will be 1310repeated for each type in the list: 1311 1312``` 1313typedef ::testing::Types<char, int, unsigned int> MyTypes; 1314TYPED_TEST_CASE(FooTest, MyTypes); 1315``` 1316 1317The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse 1318correctly. Otherwise the compiler will think that each comma in the 1319type list introduces a new macro argument. 1320 1321Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test 1322for this test case. You can repeat this as many times as you want: 1323 1324``` 1325TYPED_TEST(FooTest, DoesBlah) { 1326 // Inside a test, refer to the special name TypeParam to get the type 1327 // parameter. Since we are inside a derived class template, C++ requires 1328 // us to visit the members of FooTest via 'this'. 1329 TypeParam n = this->value_; 1330 1331 // To visit static members of the fixture, add the 'TestFixture::' 1332 // prefix. 1333 n += TestFixture::shared_; 1334 1335 // To refer to typedefs in the fixture, add the 'typename TestFixture::' 1336 // prefix. The 'typename' is required to satisfy the compiler. 1337 typename TestFixture::List values; 1338 values.push_back(n); 1339 ... 1340} 1341 1342TYPED_TEST(FooTest, HasPropertyA) { ... } 1343``` 1344 1345You can see `samples/sample6_unittest.cc` for a complete example. 1346 1347_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; 1348since version 1.1.0. 1349 1350# Type-Parameterized Tests # 1351 1352_Type-parameterized tests_ are like typed tests, except that they 1353don't require you to know the list of types ahead of time. Instead, 1354you can define the test logic first and instantiate it with different 1355type lists later. You can even instantiate it more than once in the 1356same program. 1357 1358If you are designing an interface or concept, you can define a suite 1359of type-parameterized tests to verify properties that any valid 1360implementation of the interface/concept should have. Then, the author 1361of each implementation can just instantiate the test suite with his 1362type to verify that it conforms to the requirements, without having to 1363write similar tests repeatedly. Here's an example: 1364 1365First, define a fixture class template, as we did with typed tests: 1366 1367``` 1368template <typename T> 1369class FooTest : public ::testing::Test { 1370 ... 1371}; 1372``` 1373 1374Next, declare that you will define a type-parameterized test case: 1375 1376``` 1377TYPED_TEST_CASE_P(FooTest); 1378``` 1379 1380The `_P` suffix is for "parameterized" or "pattern", whichever you 1381prefer to think. 1382 1383Then, use `TYPED_TEST_P()` to define a type-parameterized test. You 1384can repeat this as many times as you want: 1385 1386``` 1387TYPED_TEST_P(FooTest, DoesBlah) { 1388 // Inside a test, refer to TypeParam to get the type parameter. 1389 TypeParam n = 0; 1390 ... 1391} 1392 1393TYPED_TEST_P(FooTest, HasPropertyA) { ... } 1394``` 1395 1396Now the tricky part: you need to register all test patterns using the 1397`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them. 1398The first argument of the macro is the test case name; the rest are 1399the names of the tests in this test case: 1400 1401``` 1402REGISTER_TYPED_TEST_CASE_P(FooTest, 1403 DoesBlah, HasPropertyA); 1404``` 1405 1406Finally, you are free to instantiate the pattern with the types you 1407want. If you put the above code in a header file, you can `#include` 1408it in multiple C++ source files and instantiate it multiple times. 1409 1410``` 1411typedef ::testing::Types<char, int, unsigned int> MyTypes; 1412INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); 1413``` 1414 1415To distinguish different instances of the pattern, the first argument 1416to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be 1417added to the actual test case name. Remember to pick unique prefixes 1418for different instances. 1419 1420In the special case where the type list contains only one type, you 1421can write that type directly without `::testing::Types<...>`, like this: 1422 1423``` 1424INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); 1425``` 1426 1427You can see `samples/sample6_unittest.cc` for a complete example. 1428 1429_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; 1430since version 1.1.0. 1431 1432# Testing Private Code # 1433 1434If you change your software's internal implementation, your tests should not 1435break as long as the change is not observable by users. Therefore, per the 1436_black-box testing principle_, most of the time you should test your code 1437through its public interfaces. 1438 1439If you still find yourself needing to test internal implementation code, 1440consider if there's a better design that wouldn't require you to do so. If you 1441absolutely have to test non-public interface code though, you can. There are 1442two cases to consider: 1443 1444 * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and 1445 * Private or protected class members 1446 1447## Static Functions ## 1448 1449Both static functions and definitions/declarations in an unnamed namespace are 1450only visible within the same translation unit. To test them, you can `#include` 1451the entire `.cc` file being tested in your `*_test.cc` file. (`#include`ing `.cc` 1452files is not a good way to reuse code - you should not do this in production 1453code!) 1454 1455However, a better approach is to move the private code into the 1456`foo::internal` namespace, where `foo` is the namespace your project normally 1457uses, and put the private declarations in a `*-internal.h` file. Your 1458production `.cc` files and your tests are allowed to include this internal 1459header, but your clients are not. This way, you can fully test your internal 1460implementation without leaking it to your clients. 1461 1462## Private Class Members ## 1463 1464Private class members are only accessible from within the class or by friends. 1465To access a class' private members, you can declare your test fixture as a 1466friend to the class and define accessors in your fixture. Tests using the 1467fixture can then access the private members of your production class via the 1468accessors in the fixture. Note that even though your fixture is a friend to 1469your production class, your tests are not automatically friends to it, as they 1470are technically defined in sub-classes of the fixture. 1471 1472Another way to test private members is to refactor them into an implementation 1473class, which is then declared in a `*-internal.h` file. Your clients aren't 1474allowed to include this header but your tests can. Such is called the Pimpl 1475(Private Implementation) idiom. 1476 1477Or, you can declare an individual test as a friend of your class by adding this 1478line in the class body: 1479 1480``` 1481FRIEND_TEST(TestCaseName, TestName); 1482``` 1483 1484For example, 1485``` 1486// foo.h 1487#include "gtest/gtest_prod.h" 1488 1489// Defines FRIEND_TEST. 1490class Foo { 1491 ... 1492 private: 1493 FRIEND_TEST(FooTest, BarReturnsZeroOnNull); 1494 int Bar(void* x); 1495}; 1496 1497// foo_test.cc 1498... 1499TEST(FooTest, BarReturnsZeroOnNull) { 1500 Foo foo; 1501 EXPECT_EQ(0, foo.Bar(NULL)); 1502 // Uses Foo's private member Bar(). 1503} 1504``` 1505 1506Pay special attention when your class is defined in a namespace, as you should 1507define your test fixtures and tests in the same namespace if you want them to 1508be friends of your class. For example, if the code to be tested looks like: 1509 1510``` 1511namespace my_namespace { 1512 1513class Foo { 1514 friend class FooTest; 1515 FRIEND_TEST(FooTest, Bar); 1516 FRIEND_TEST(FooTest, Baz); 1517 ... 1518 definition of the class Foo 1519 ... 1520}; 1521 1522} // namespace my_namespace 1523``` 1524 1525Your test code should be something like: 1526 1527``` 1528namespace my_namespace { 1529class FooTest : public ::testing::Test { 1530 protected: 1531 ... 1532}; 1533 1534TEST_F(FooTest, Bar) { ... } 1535TEST_F(FooTest, Baz) { ... } 1536 1537} // namespace my_namespace 1538``` 1539 1540# Catching Failures # 1541 1542If you are building a testing utility on top of Google Test, you'll 1543want to test your utility. What framework would you use to test it? 1544Google Test, of course. 1545 1546The challenge is to verify that your testing utility reports failures 1547correctly. In frameworks that report a failure by throwing an 1548exception, you could catch the exception and assert on it. But Google 1549Test doesn't use exceptions, so how do we test that a piece of code 1550generates an expected failure? 1551 1552`"gtest/gtest-spi.h"` contains some constructs to do this. After 1553`#include`ing this header, you can use 1554 1555| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` | 1556|:--------------------------------------------------| 1557 1558to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure 1559whose message contains the given _substring_, or use 1560 1561| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` | 1562|:-----------------------------------------------------| 1563 1564if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. 1565 1566For technical reasons, there are some caveats: 1567 1568 1. You cannot stream a failure message to either macro. 1569 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object. 1570 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value. 1571 1572_Note:_ Google Test is designed with threads in mind. Once the 1573synchronization primitives in `"gtest/internal/gtest-port.h"` have 1574been implemented, Google Test will become thread-safe, meaning that 1575you can then use assertions in multiple threads concurrently. Before 1576 1577that, however, Google Test only supports single-threaded usage. Once 1578thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()` 1579will capture failures in the current thread only. If _statement_ 1580creates new threads, failures in these threads will be ignored. If 1581you want to capture failures from all threads instead, you should use 1582the following macros: 1583 1584| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | 1585|:-----------------------------------------------------------------| 1586| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | 1587 1588# Getting the Current Test's Name # 1589 1590Sometimes a function may need to know the name of the currently running test. 1591For example, you may be using the `SetUp()` method of your test fixture to set 1592the golden file name based on which test is running. The `::testing::TestInfo` 1593class has this information: 1594 1595``` 1596namespace testing { 1597 1598class TestInfo { 1599 public: 1600 // Returns the test case name and the test name, respectively. 1601 // 1602 // Do NOT delete or free the return value - it's managed by the 1603 // TestInfo class. 1604 const char* test_case_name() const; 1605 const char* name() const; 1606}; 1607 1608} // namespace testing 1609``` 1610 1611 1612> To obtain a `TestInfo` object for the currently running test, call 1613`current_test_info()` on the `UnitTest` singleton object: 1614 1615``` 1616// Gets information about the currently running test. 1617// Do NOT delete the returned object - it's managed by the UnitTest class. 1618const ::testing::TestInfo* const test_info = 1619 ::testing::UnitTest::GetInstance()->current_test_info(); 1620printf("We are in test %s of test case %s.\n", 1621 test_info->name(), test_info->test_case_name()); 1622``` 1623 1624`current_test_info()` returns a null pointer if no test is running. In 1625particular, you cannot find the test case name in `TestCaseSetUp()`, 1626`TestCaseTearDown()` (where you know the test case name implicitly), or 1627functions called from them. 1628 1629_Availability:_ Linux, Windows, Mac. 1630 1631# Extending Google Test by Handling Test Events # 1632 1633Google Test provides an <b>event listener API</b> to let you receive 1634notifications about the progress of a test program and test 1635failures. The events you can listen to include the start and end of 1636the test program, a test case, or a test method, among others. You may 1637use this API to augment or replace the standard console output, 1638replace the XML output, or provide a completely different form of 1639output, such as a GUI or a database. You can also use test events as 1640checkpoints to implement a resource leak checker, for example. 1641 1642_Availability:_ Linux, Windows, Mac; since v1.4.0. 1643 1644## Defining Event Listeners ## 1645 1646To define a event listener, you subclass either 1647[testing::TestEventListener](../include/gtest/gtest.h#L855) 1648or [testing::EmptyTestEventListener](../include/gtest/gtest.h#L905). 1649The former is an (abstract) interface, where <i>each pure virtual method<br> 1650can be overridden to handle a test event</i> (For example, when a test 1651starts, the `OnTestStart()` method will be called.). The latter provides 1652an empty implementation of all methods in the interface, such that a 1653subclass only needs to override the methods it cares about. 1654 1655When an event is fired, its context is passed to the handler function 1656as an argument. The following argument types are used: 1657 * [UnitTest](../include/gtest/gtest.h#L1007) reflects the state of the entire test program, 1658 * [TestCase](../include/gtest/gtest.h#L689) has information about a test case, which can contain one or more tests, 1659 * [TestInfo](../include/gtest/gtest.h#L599) contains the state of a test, and 1660 * [TestPartResult](../include/gtest/gtest-test-part.h#L42) represents the result of a test assertion. 1661 1662An event handler function can examine the argument it receives to find 1663out interesting information about the event and the test program's 1664state. Here's an example: 1665 1666``` 1667 class MinimalistPrinter : public ::testing::EmptyTestEventListener { 1668 // Called before a test starts. 1669 virtual void OnTestStart(const ::testing::TestInfo& test_info) { 1670 printf("*** Test %s.%s starting.\n", 1671 test_info.test_case_name(), test_info.name()); 1672 } 1673 1674 // Called after a failed assertion or a SUCCEED() invocation. 1675 virtual void OnTestPartResult( 1676 const ::testing::TestPartResult& test_part_result) { 1677 printf("%s in %s:%d\n%s\n", 1678 test_part_result.failed() ? "*** Failure" : "Success", 1679 test_part_result.file_name(), 1680 test_part_result.line_number(), 1681 test_part_result.summary()); 1682 } 1683 1684 // Called after a test ends. 1685 virtual void OnTestEnd(const ::testing::TestInfo& test_info) { 1686 printf("*** Test %s.%s ending.\n", 1687 test_info.test_case_name(), test_info.name()); 1688 } 1689 }; 1690``` 1691 1692## Using Event Listeners ## 1693 1694To use the event listener you have defined, add an instance of it to 1695the Google Test event listener list (represented by class 1696[TestEventListeners](../include/gtest/gtest.h#L929) 1697- note the "s" at the end of the name) in your 1698`main()` function, before calling `RUN_ALL_TESTS()`: 1699``` 1700int main(int argc, char** argv) { 1701 ::testing::InitGoogleTest(&argc, argv); 1702 // Gets hold of the event listener list. 1703 ::testing::TestEventListeners& listeners = 1704 ::testing::UnitTest::GetInstance()->listeners(); 1705 // Adds a listener to the end. Google Test takes the ownership. 1706 listeners.Append(new MinimalistPrinter); 1707 return RUN_ALL_TESTS(); 1708} 1709``` 1710 1711There's only one problem: the default test result printer is still in 1712effect, so its output will mingle with the output from your minimalist 1713printer. To suppress the default printer, just release it from the 1714event listener list and delete it. You can do so by adding one line: 1715``` 1716 ... 1717 delete listeners.Release(listeners.default_result_printer()); 1718 listeners.Append(new MinimalistPrinter); 1719 return RUN_ALL_TESTS(); 1720``` 1721 1722Now, sit back and enjoy a completely different output from your 1723tests. For more details, you can read this 1724[sample](../samples/sample9_unittest.cc). 1725 1726You may append more than one listener to the list. When an `On*Start()` 1727or `OnTestPartResult()` event is fired, the listeners will receive it in 1728the order they appear in the list (since new listeners are added to 1729the end of the list, the default text printer and the default XML 1730generator will receive the event first). An `On*End()` event will be 1731received by the listeners in the _reverse_ order. This allows output by 1732listeners added later to be framed by output from listeners added 1733earlier. 1734 1735## Generating Failures in Listeners ## 1736 1737You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, 1738`FAIL()`, etc) when processing an event. There are some restrictions: 1739 1740 1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively). 1741 1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure. 1742 1743When you add listeners to the listener list, you should put listeners 1744that handle `OnTestPartResult()` _before_ listeners that can generate 1745failures. This ensures that failures generated by the latter are 1746attributed to the right test by the former. 1747 1748We have a sample of failure-raising listener 1749[here](../samples/sample10_unittest.cc). 1750 1751# Running Test Programs: Advanced Options # 1752 1753Google Test test programs are ordinary executables. Once built, you can run 1754them directly and affect their behavior via the following environment variables 1755and/or command line flags. For the flags to work, your programs must call 1756`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. 1757 1758To see a list of supported flags and their usage, please run your test 1759program with the `--help` flag. You can also use `-h`, `-?`, or `/?` 1760for short. This feature is added in version 1.3.0. 1761 1762If an option is specified both by an environment variable and by a 1763flag, the latter takes precedence. Most of the options can also be 1764set/read in code: to access the value of command line flag 1765`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`. A common pattern is 1766to set the value of a flag before calling `::testing::InitGoogleTest()` 1767to change the default value of the flag: 1768``` 1769int main(int argc, char** argv) { 1770 // Disables elapsed time by default. 1771 ::testing::GTEST_FLAG(print_time) = false; 1772 1773 // This allows the user to override the flag on the command line. 1774 ::testing::InitGoogleTest(&argc, argv); 1775 1776 return RUN_ALL_TESTS(); 1777} 1778``` 1779 1780## Selecting Tests ## 1781 1782This section shows various options for choosing which tests to run. 1783 1784### Listing Test Names ### 1785 1786Sometimes it is necessary to list the available tests in a program before 1787running them so that a filter may be applied if needed. Including the flag 1788`--gtest_list_tests` overrides all other flags and lists tests in the following 1789format: 1790``` 1791TestCase1. 1792 TestName1 1793 TestName2 1794TestCase2. 1795 TestName 1796``` 1797 1798None of the tests listed are actually run if the flag is provided. There is no 1799corresponding environment variable for this flag. 1800 1801_Availability:_ Linux, Windows, Mac. 1802 1803### Running a Subset of the Tests ### 1804 1805By default, a Google Test program runs all tests the user has defined. 1806Sometimes, you want to run only a subset of the tests (e.g. for debugging or 1807quickly verifying a change). If you set the `GTEST_FILTER` environment variable 1808or the `--gtest_filter` flag to a filter string, Google Test will only run the 1809tests whose full names (in the form of `TestCaseName.TestName`) match the 1810filter. 1811 1812The format of a filter is a '`:`'-separated list of wildcard patterns (called 1813the positive patterns) optionally followed by a '`-`' and another 1814'`:`'-separated pattern list (called the negative patterns). A test matches the 1815filter if and only if it matches any of the positive patterns but does not 1816match any of the negative patterns. 1817 1818A pattern may contain `'*'` (matches any string) or `'?'` (matches any single 1819character). For convenience, the filter `'*-NegativePatterns'` can be also 1820written as `'-NegativePatterns'`. 1821 1822For example: 1823 1824 * `./foo_test` Has no flag, and thus runs all its tests. 1825 * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value. 1826 * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`. 1827 * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`. 1828 * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. 1829 * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`. 1830 1831_Availability:_ Linux, Windows, Mac. 1832 1833### Temporarily Disabling Tests ### 1834 1835If you have a broken test that you cannot fix right away, you can add the 1836`DISABLED_` prefix to its name. This will exclude it from execution. This is 1837better than commenting out the code or using `#if 0`, as disabled tests are 1838still compiled (and thus won't rot). 1839 1840If you need to disable all tests in a test case, you can either add `DISABLED_` 1841to the front of the name of each test, or alternatively add it to the front of 1842the test case name. 1843 1844For example, the following tests won't be run by Google Test, even though they 1845will still be compiled: 1846 1847``` 1848// Tests that Foo does Abc. 1849TEST(FooTest, DISABLED_DoesAbc) { ... } 1850 1851class DISABLED_BarTest : public ::testing::Test { ... }; 1852 1853// Tests that Bar does Xyz. 1854TEST_F(DISABLED_BarTest, DoesXyz) { ... } 1855``` 1856 1857_Note:_ This feature should only be used for temporary pain-relief. You still 1858have to fix the disabled tests at a later date. As a reminder, Google Test will 1859print a banner warning you if a test program contains any disabled tests. 1860 1861_Tip:_ You can easily count the number of disabled tests you have 1862using `grep`. This number can be used as a metric for improving your 1863test quality. 1864 1865_Availability:_ Linux, Windows, Mac. 1866 1867### Temporarily Enabling Disabled Tests ### 1868 1869To include [disabled tests](#temporarily-disabling-tests) in test 1870execution, just invoke the test program with the 1871`--gtest_also_run_disabled_tests` flag or set the 1872`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other 1873than `0`. You can combine this with the 1874[--gtest\_filter](#running-a-subset-of-the-tests) flag to further select 1875which disabled tests to run. 1876 1877_Availability:_ Linux, Windows, Mac; since version 1.3.0. 1878 1879## Repeating the Tests ## 1880 1881Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it 1882will fail only 1% of the time, making it rather hard to reproduce the bug under 1883a debugger. This can be a major source of frustration. 1884 1885The `--gtest_repeat` flag allows you to repeat all (or selected) test methods 1886in a program many times. Hopefully, a flaky test will eventually fail and give 1887you a chance to debug. Here's how to use it: 1888 1889| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. | 1890|:---------------------------------|:--------------------------------------------------------| 1891| `$ foo_test --gtest_repeat=-1` | A negative count means repeating forever. | 1892| `$ foo_test --gtest_repeat=1000 --gtest_break_on_failure` | Repeat foo\_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the testfails, it will drop into the debugger and you can then inspect variables and stacks. | 1893| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. | 1894 1895If your test program contains global set-up/tear-down code registered 1896using `AddGlobalTestEnvironment()`, it will be repeated in each 1897iteration as well, as the flakiness may be in it. You can also specify 1898the repeat count by setting the `GTEST_REPEAT` environment variable. 1899 1900_Availability:_ Linux, Windows, Mac. 1901 1902## Shuffling the Tests ## 1903 1904You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` 1905environment variable to `1`) to run the tests in a program in a random 1906order. This helps to reveal bad dependencies between tests. 1907 1908By default, Google Test uses a random seed calculated from the current 1909time. Therefore you'll get a different order every time. The console 1910output includes the random seed value, such that you can reproduce an 1911order-related test failure later. To specify the random seed 1912explicitly, use the `--gtest_random_seed=SEED` flag (or set the 1913`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer 1914between 0 and 99999. The seed value 0 is special: it tells Google Test 1915to do the default behavior of calculating the seed from the current 1916time. 1917 1918If you combine this with `--gtest_repeat=N`, Google Test will pick a 1919different random seed and re-shuffle the tests in each iteration. 1920 1921_Availability:_ Linux, Windows, Mac; since v1.4.0. 1922 1923## Controlling Test Output ## 1924 1925This section teaches how to tweak the way test results are reported. 1926 1927### Colored Terminal Output ### 1928 1929Google Test can use colors in its terminal output to make it easier to spot 1930the separation between tests, and whether tests passed. 1931 1932You can set the GTEST\_COLOR environment variable or set the `--gtest_color` 1933command line flag to `yes`, `no`, or `auto` (the default) to enable colors, 1934disable colors, or let Google Test decide. When the value is `auto`, Google 1935Test will use colors if and only if the output goes to a terminal and (on 1936non-Windows platforms) the `TERM` environment variable is set to `xterm` or 1937`xterm-color`. 1938 1939_Availability:_ Linux, Windows, Mac. 1940 1941### Suppressing the Elapsed Time ### 1942 1943By default, Google Test prints the time it takes to run each test. To 1944suppress that, run the test program with the `--gtest_print_time=0` 1945command line flag. Setting the `GTEST_PRINT_TIME` environment 1946variable to `0` has the same effect. 1947 1948_Availability:_ Linux, Windows, Mac. (In Google Test 1.3.0 and lower, 1949the default behavior is that the elapsed time is **not** printed.) 1950 1951### Generating an XML Report ### 1952 1953Google Test can emit a detailed XML report to a file in addition to its normal 1954textual output. The report contains the duration of each test, and thus can 1955help you identify slow tests. 1956 1957To generate the XML report, set the `GTEST_OUTPUT` environment variable or the 1958`--gtest_output` flag to the string `"xml:_path_to_output_file_"`, which will 1959create the file at the given location. You can also just use the string 1960`"xml"`, in which case the output can be found in the `test_detail.xml` file in 1961the current directory. 1962 1963If you specify a directory (for example, `"xml:output/directory/"` on Linux or 1964`"xml:output\directory\"` on Windows), Google Test will create the XML file in 1965that directory, named after the test executable (e.g. `foo_test.xml` for test 1966program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left 1967over from a previous run), Google Test will pick a different name (e.g. 1968`foo_test_1.xml`) to avoid overwriting it. 1969 1970The report uses the format described here. It is based on the 1971`junitreport` Ant task and can be parsed by popular continuous build 1972systems like [Jenkins](http://jenkins-ci.org/). Since that format 1973was originally intended for Java, a little interpretation is required 1974to make it apply to Google Test tests, as shown here: 1975 1976``` 1977<testsuites name="AllTests" ...> 1978 <testsuite name="test_case_name" ...> 1979 <testcase name="test_name" ...> 1980 <failure message="..."/> 1981 <failure message="..."/> 1982 <failure message="..."/> 1983 </testcase> 1984 </testsuite> 1985</testsuites> 1986``` 1987 1988 * The root `<testsuites>` element corresponds to the entire test program. 1989 * `<testsuite>` elements correspond to Google Test test cases. 1990 * `<testcase>` elements correspond to Google Test test functions. 1991 1992For instance, the following program 1993 1994``` 1995TEST(MathTest, Addition) { ... } 1996TEST(MathTest, Subtraction) { ... } 1997TEST(LogicTest, NonContradiction) { ... } 1998``` 1999 2000could generate this report: 2001 2002``` 2003<?xml version="1.0" encoding="UTF-8"?> 2004<testsuites tests="3" failures="1" errors="0" time="35" name="AllTests"> 2005 <testsuite name="MathTest" tests="2" failures="1" errors="0" time="15"> 2006 <testcase name="Addition" status="run" time="7" classname=""> 2007 <failure message="Value of: add(1, 1)
 Actual: 3
Expected: 2" type=""/> 2008 <failure message="Value of: add(1, -1)
 Actual: 1
Expected: 0" type=""/> 2009 </testcase> 2010 <testcase name="Subtraction" status="run" time="5" classname=""> 2011 </testcase> 2012 </testsuite> 2013 <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5"> 2014 <testcase name="NonContradiction" status="run" time="5" classname=""> 2015 </testcase> 2016 </testsuite> 2017</testsuites> 2018``` 2019 2020Things to note: 2021 2022 * The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how many test functions the Google Test program or test case contains, while the `failures` attribute tells how many of them failed. 2023 * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds. 2024 * Each `<failure>` element corresponds to a single failed Google Test assertion. 2025 * Some JUnit concepts don't apply to Google Test, yet we have to conform to the DTD. Therefore you'll see some dummy elements and attributes in the report. You can safely ignore these parts. 2026 2027_Availability:_ Linux, Windows, Mac. 2028 2029## Controlling How Failures Are Reported ## 2030 2031### Turning Assertion Failures into Break-Points ### 2032 2033When running test programs under a debugger, it's very convenient if the 2034debugger can catch an assertion failure and automatically drop into interactive 2035mode. Google Test's _break-on-failure_ mode supports this behavior. 2036 2037To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value 2038other than `0` . Alternatively, you can use the `--gtest_break_on_failure` 2039command line flag. 2040 2041_Availability:_ Linux, Windows, Mac. 2042 2043### Disabling Catching Test-Thrown Exceptions ### 2044 2045Google Test can be used either with or without exceptions enabled. If 2046a test throws a C++ exception or (on Windows) a structured exception 2047(SEH), by default Google Test catches it, reports it as a test 2048failure, and continues with the next test method. This maximizes the 2049coverage of a test run. Also, on Windows an uncaught exception will 2050cause a pop-up window, so catching the exceptions allows you to run 2051the tests automatically. 2052 2053When debugging the test failures, however, you may instead want the 2054exceptions to be handled by the debugger, such that you can examine 2055the call stack when an exception is thrown. To achieve that, set the 2056`GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the 2057`--gtest_catch_exceptions=0` flag when running the tests. 2058 2059**Availability**: Linux, Windows, Mac. 2060 2061### Letting Another Testing Framework Drive ### 2062 2063If you work on a project that has already been using another testing 2064framework and is not ready to completely switch to Google Test yet, 2065you can get much of Google Test's benefit by using its assertions in 2066your existing tests. Just change your `main()` function to look 2067like: 2068 2069``` 2070#include "gtest/gtest.h" 2071 2072int main(int argc, char** argv) { 2073 ::testing::GTEST_FLAG(throw_on_failure) = true; 2074 // Important: Google Test must be initialized. 2075 ::testing::InitGoogleTest(&argc, argv); 2076 2077 ... whatever your existing testing framework requires ... 2078} 2079``` 2080 2081With that, you can use Google Test assertions in addition to the 2082native assertions your testing framework provides, for example: 2083 2084``` 2085void TestFooDoesBar() { 2086 Foo foo; 2087 EXPECT_LE(foo.Bar(1), 100); // A Google Test assertion. 2088 CPPUNIT_ASSERT(foo.IsEmpty()); // A native assertion. 2089} 2090``` 2091 2092If a Google Test assertion fails, it will print an error message and 2093throw an exception, which will be treated as a failure by your host 2094testing framework. If you compile your code with exceptions disabled, 2095a failed Google Test assertion will instead exit your program with a 2096non-zero code, which will also signal a test failure to your test 2097runner. 2098 2099If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in 2100your `main()`, you can alternatively enable this feature by specifying 2101the `--gtest_throw_on_failure` flag on the command-line or setting the 2102`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value. 2103 2104Death tests are _not_ supported when other test framework is used to organize tests. 2105 2106_Availability:_ Linux, Windows, Mac; since v1.3.0. 2107 2108## Distributing Test Functions to Multiple Machines ## 2109 2110If you have more than one machine you can use to run a test program, 2111you might want to run the test functions in parallel and get the 2112result faster. We call this technique _sharding_, where each machine 2113is called a _shard_. 2114 2115Google Test is compatible with test sharding. To take advantage of 2116this feature, your test runner (not part of Google Test) needs to do 2117the following: 2118 2119 1. Allocate a number of machines (shards) to run the tests. 2120 1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total number of shards. It must be the same for all shards. 2121 1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index of the shard. Different shards must be assigned different indices, which must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. 2122 1. Run the same test program on all shards. When Google Test sees the above two environment variables, it will select a subset of the test functions to run. Across all shards, each test function in the program will be run exactly once. 2123 1. Wait for all shards to finish, then collect and report the results. 2124 2125Your project may have tests that were written without Google Test and 2126thus don't understand this protocol. In order for your test runner to 2127figure out which test supports sharding, it can set the environment 2128variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path. If a 2129test program supports sharding, it will create this file to 2130acknowledge the fact (the actual contents of the file are not 2131important at this time; although we may stick some useful information 2132in it in the future.); otherwise it will not create it. 2133 2134Here's an example to make it clear. Suppose you have a test program 2135`foo_test` that contains the following 5 test functions: 2136``` 2137TEST(A, V) 2138TEST(A, W) 2139TEST(B, X) 2140TEST(B, Y) 2141TEST(B, Z) 2142``` 2143and you have 3 machines at your disposal. To run the test functions in 2144parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and 2145set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. 2146Then you would run the same `foo_test` on each machine. 2147 2148Google Test reserves the right to change how the work is distributed 2149across the shards, but here's one possible scenario: 2150 2151 * Machine #0 runs `A.V` and `B.X`. 2152 * Machine #1 runs `A.W` and `B.Y`. 2153 * Machine #2 runs `B.Z`. 2154 2155_Availability:_ Linux, Windows, Mac; since version 1.3.0. 2156 2157# Fusing Google Test Source Files # 2158 2159Google Test's implementation consists of ~30 files (excluding its own 2160tests). Sometimes you may want them to be packaged up in two files (a 2161`.h` and a `.cc`) instead, such that you can easily copy them to a new 2162machine and start hacking there. For this we provide an experimental 2163Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0). 2164Assuming you have Python 2.4 or above installed on your machine, just 2165go to that directory and run 2166``` 2167python fuse_gtest_files.py OUTPUT_DIR 2168``` 2169 2170and you should see an `OUTPUT_DIR` directory being created with files 2171`gtest/gtest.h` and `gtest/gtest-all.cc` in it. These files contain 2172everything you need to use Google Test. Just copy them to anywhere 2173you want and you are ready to write tests. You can use the 2174[scripts/test/Makefile](../scripts/test/Makefile) 2175file as an example on how to compile your tests against them. 2176 2177# Where to Go from Here # 2178 2179Congratulations! You've now learned more advanced Google Test tools and are 2180ready to tackle more complex testing tasks. If you want to dive even deeper, you 2181can read the [Frequently-Asked Questions](V1_7_FAQ.md). 2182