113481Sgiacomo.travaglini@arm.com
213481Sgiacomo.travaglini@arm.com
313481Sgiacomo.travaglini@arm.comNow that you have read [Primer](V1_7_Primer.md) and learned how to write tests
413481Sgiacomo.travaglini@arm.comusing Google Test, it's time to learn some new tricks. This document
513481Sgiacomo.travaglini@arm.comwill show you more assertions as well as how to construct complex
613481Sgiacomo.travaglini@arm.comfailure messages, propagate fatal failures, reuse and speed up your
713481Sgiacomo.travaglini@arm.comtest fixtures, and use various flags with your tests.
813481Sgiacomo.travaglini@arm.com
913481Sgiacomo.travaglini@arm.com# More Assertions #
1013481Sgiacomo.travaglini@arm.com
1113481Sgiacomo.travaglini@arm.comThis section covers some less frequently used, but still significant,
1213481Sgiacomo.travaglini@arm.comassertions.
1313481Sgiacomo.travaglini@arm.com
1413481Sgiacomo.travaglini@arm.com## Explicit Success and Failure ##
1513481Sgiacomo.travaglini@arm.com
1613481Sgiacomo.travaglini@arm.comThese three assertions do not actually test a value or expression. Instead,
1713481Sgiacomo.travaglini@arm.comthey generate a success or failure directly. Like the macros that actually
1813481Sgiacomo.travaglini@arm.comperform a test, you may stream a custom failure message into the them.
1913481Sgiacomo.travaglini@arm.com
2013481Sgiacomo.travaglini@arm.com| `SUCCEED();` |
2113481Sgiacomo.travaglini@arm.com|:-------------|
2213481Sgiacomo.travaglini@arm.com
2313481Sgiacomo.travaglini@arm.comGenerates a success. This does NOT make the overall test succeed. A test is
2413481Sgiacomo.travaglini@arm.comconsidered successful only if none of its assertions fail during its execution.
2513481Sgiacomo.travaglini@arm.com
2613481Sgiacomo.travaglini@arm.comNote: `SUCCEED()` is purely documentary and currently doesn't generate any
2713481Sgiacomo.travaglini@arm.comuser-visible output. However, we may add `SUCCEED()` messages to Google Test's
2813481Sgiacomo.travaglini@arm.comoutput in the future.
2913481Sgiacomo.travaglini@arm.com
3013481Sgiacomo.travaglini@arm.com| `FAIL();`  | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` |
3113481Sgiacomo.travaglini@arm.com|:-----------|:-----------------|:------------------------------------------------------|
3213481Sgiacomo.travaglini@arm.com
3313481Sgiacomo.travaglini@arm.com`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal
3413481Sgiacomo.travaglini@arm.comfailure. These are useful when control flow, rather than a Boolean expression,
3513481Sgiacomo.travaglini@arm.comdeteremines the test's success or failure. For example, you might want to write
3613481Sgiacomo.travaglini@arm.comsomething like:
3713481Sgiacomo.travaglini@arm.com
3813481Sgiacomo.travaglini@arm.com```
3913481Sgiacomo.travaglini@arm.comswitch(expression) {
4013481Sgiacomo.travaglini@arm.com  case 1: ... some checks ...
4113481Sgiacomo.travaglini@arm.com  case 2: ... some other checks
4213481Sgiacomo.travaglini@arm.com  ...
4313481Sgiacomo.travaglini@arm.com  default: FAIL() << "We shouldn't get here.";
4413481Sgiacomo.travaglini@arm.com}
4513481Sgiacomo.travaglini@arm.com```
4613481Sgiacomo.travaglini@arm.com
4713481Sgiacomo.travaglini@arm.com_Availability_: Linux, Windows, Mac.
4813481Sgiacomo.travaglini@arm.com
4913481Sgiacomo.travaglini@arm.com## Exception Assertions ##
5013481Sgiacomo.travaglini@arm.com
5113481Sgiacomo.travaglini@arm.comThese are for verifying that a piece of code throws (or does not
5213481Sgiacomo.travaglini@arm.comthrow) an exception of the given type:
5313481Sgiacomo.travaglini@arm.com
5413481Sgiacomo.travaglini@arm.com| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
5513481Sgiacomo.travaglini@arm.com|:--------------------|:-----------------------|:-------------|
5613481Sgiacomo.travaglini@arm.com| `ASSERT_THROW(`_statement_, _exception\_type_`);`  | `EXPECT_THROW(`_statement_, _exception\_type_`);`  | _statement_ throws an exception of the given type  |
5713481Sgiacomo.travaglini@arm.com| `ASSERT_ANY_THROW(`_statement_`);`                | `EXPECT_ANY_THROW(`_statement_`);`                | _statement_ throws an exception of any type        |
5813481Sgiacomo.travaglini@arm.com| `ASSERT_NO_THROW(`_statement_`);`                 | `EXPECT_NO_THROW(`_statement_`);`                 | _statement_ doesn't throw any exception            |
5913481Sgiacomo.travaglini@arm.com
6013481Sgiacomo.travaglini@arm.comExamples:
6113481Sgiacomo.travaglini@arm.com
6213481Sgiacomo.travaglini@arm.com```
6313481Sgiacomo.travaglini@arm.comASSERT_THROW(Foo(5), bar_exception);
6413481Sgiacomo.travaglini@arm.com
6513481Sgiacomo.travaglini@arm.comEXPECT_NO_THROW({
6613481Sgiacomo.travaglini@arm.com  int n = 5;
6713481Sgiacomo.travaglini@arm.com  Bar(&n);
6813481Sgiacomo.travaglini@arm.com});
6913481Sgiacomo.travaglini@arm.com```
7013481Sgiacomo.travaglini@arm.com
7113481Sgiacomo.travaglini@arm.com_Availability_: Linux, Windows, Mac; since version 1.1.0.
7213481Sgiacomo.travaglini@arm.com
7313481Sgiacomo.travaglini@arm.com## Predicate Assertions for Better Error Messages ##
7413481Sgiacomo.travaglini@arm.com
7513481Sgiacomo.travaglini@arm.comEven though Google Test has a rich set of assertions, they can never be
7613481Sgiacomo.travaglini@arm.comcomplete, as it's impossible (nor a good idea) to anticipate all the scenarios
7713481Sgiacomo.travaglini@arm.coma user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()`
7813481Sgiacomo.travaglini@arm.comto check a complex expression, for lack of a better macro. This has the problem
7913481Sgiacomo.travaglini@arm.comof not showing you the values of the parts of the expression, making it hard to
8013481Sgiacomo.travaglini@arm.comunderstand what went wrong. As a workaround, some users choose to construct the
8113481Sgiacomo.travaglini@arm.comfailure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
8213481Sgiacomo.travaglini@arm.comis awkward especially when the expression has side-effects or is expensive to
8313481Sgiacomo.travaglini@arm.comevaluate.
8413481Sgiacomo.travaglini@arm.com
8513481Sgiacomo.travaglini@arm.comGoogle Test gives you three different options to solve this problem:
8613481Sgiacomo.travaglini@arm.com
8713481Sgiacomo.travaglini@arm.com### Using an Existing Boolean Function ###
8813481Sgiacomo.travaglini@arm.com
8913481Sgiacomo.travaglini@arm.comIf you already have a function or a functor that returns `bool` (or a type
9013481Sgiacomo.travaglini@arm.comthat can be implicitly converted to `bool`), you can use it in a _predicate
9113481Sgiacomo.travaglini@arm.comassertion_ to get the function arguments printed for free:
9213481Sgiacomo.travaglini@arm.com
9313481Sgiacomo.travaglini@arm.com| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
9413481Sgiacomo.travaglini@arm.com|:--------------------|:-----------------------|:-------------|
9513481Sgiacomo.travaglini@arm.com| `ASSERT_PRED1(`_pred1, val1_`);`       | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true |
9613481Sgiacomo.travaglini@arm.com| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` |  _pred2(val1, val2)_ returns true |
9713481Sgiacomo.travaglini@arm.com|  ...                | ...                    | ...          |
9813481Sgiacomo.travaglini@arm.com
9913481Sgiacomo.travaglini@arm.comIn the above, _predn_ is an _n_-ary predicate function or functor, where
10013481Sgiacomo.travaglini@arm.com_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds
10113481Sgiacomo.travaglini@arm.comif the predicate returns `true` when applied to the given arguments, and fails
10213481Sgiacomo.travaglini@arm.comotherwise. When the assertion fails, it prints the value of each argument. In
10313481Sgiacomo.travaglini@arm.comeither case, the arguments are evaluated exactly once.
10413481Sgiacomo.travaglini@arm.com
10513481Sgiacomo.travaglini@arm.comHere's an example. Given
10613481Sgiacomo.travaglini@arm.com
10713481Sgiacomo.travaglini@arm.com```
10813481Sgiacomo.travaglini@arm.com// Returns true iff m and n have no common divisors except 1.
10913481Sgiacomo.travaglini@arm.combool MutuallyPrime(int m, int n) { ... }
11013481Sgiacomo.travaglini@arm.comconst int a = 3;
11113481Sgiacomo.travaglini@arm.comconst int b = 4;
11213481Sgiacomo.travaglini@arm.comconst int c = 10;
11313481Sgiacomo.travaglini@arm.com```
11413481Sgiacomo.travaglini@arm.com
11513481Sgiacomo.travaglini@arm.comthe assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the
11613481Sgiacomo.travaglini@arm.comassertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message
11713481Sgiacomo.travaglini@arm.com
11813481Sgiacomo.travaglini@arm.com<pre>
11913481Sgiacomo.travaglini@arm.com!MutuallyPrime(b, c) is false, where<br>
12013481Sgiacomo.travaglini@arm.comb is 4<br>
12113481Sgiacomo.travaglini@arm.comc is 10<br>
12213481Sgiacomo.travaglini@arm.com</pre>
12313481Sgiacomo.travaglini@arm.com
12413481Sgiacomo.travaglini@arm.com**Notes:**
12513481Sgiacomo.travaglini@arm.com
12613481Sgiacomo.travaglini@arm.com  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.
12713481Sgiacomo.travaglini@arm.com  1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know.
12813481Sgiacomo.travaglini@arm.com
12913481Sgiacomo.travaglini@arm.com_Availability_: Linux, Windows, Mac
13013481Sgiacomo.travaglini@arm.com
13113481Sgiacomo.travaglini@arm.com### Using a Function That Returns an AssertionResult ###
13213481Sgiacomo.travaglini@arm.com
13313481Sgiacomo.travaglini@arm.comWhile `EXPECT_PRED*()` and friends are handy for a quick job, the
13413481Sgiacomo.travaglini@arm.comsyntax is not satisfactory: you have to use different macros for
13513481Sgiacomo.travaglini@arm.comdifferent arities, and it feels more like Lisp than C++.  The
13613481Sgiacomo.travaglini@arm.com`::testing::AssertionResult` class solves this problem.
13713481Sgiacomo.travaglini@arm.com
13813481Sgiacomo.travaglini@arm.comAn `AssertionResult` object represents the result of an assertion
13913481Sgiacomo.travaglini@arm.com(whether it's a success or a failure, and an associated message).  You
14013481Sgiacomo.travaglini@arm.comcan create an `AssertionResult` using one of these factory
14113481Sgiacomo.travaglini@arm.comfunctions:
14213481Sgiacomo.travaglini@arm.com
14313481Sgiacomo.travaglini@arm.com```
14413481Sgiacomo.travaglini@arm.comnamespace testing {
14513481Sgiacomo.travaglini@arm.com
14613481Sgiacomo.travaglini@arm.com// Returns an AssertionResult object to indicate that an assertion has
14713481Sgiacomo.travaglini@arm.com// succeeded.
14813481Sgiacomo.travaglini@arm.comAssertionResult AssertionSuccess();
14913481Sgiacomo.travaglini@arm.com
15013481Sgiacomo.travaglini@arm.com// Returns an AssertionResult object to indicate that an assertion has
15113481Sgiacomo.travaglini@arm.com// failed.
15213481Sgiacomo.travaglini@arm.comAssertionResult AssertionFailure();
15313481Sgiacomo.travaglini@arm.com
15413481Sgiacomo.travaglini@arm.com}
15513481Sgiacomo.travaglini@arm.com```
15613481Sgiacomo.travaglini@arm.com
15713481Sgiacomo.travaglini@arm.comYou can then use the `<<` operator to stream messages to the
15813481Sgiacomo.travaglini@arm.com`AssertionResult` object.
15913481Sgiacomo.travaglini@arm.com
16013481Sgiacomo.travaglini@arm.comTo provide more readable messages in Boolean assertions
16113481Sgiacomo.travaglini@arm.com(e.g. `EXPECT_TRUE()`), write a predicate function that returns
16213481Sgiacomo.travaglini@arm.com`AssertionResult` instead of `bool`. For example, if you define
16313481Sgiacomo.travaglini@arm.com`IsEven()` as:
16413481Sgiacomo.travaglini@arm.com
16513481Sgiacomo.travaglini@arm.com```
16613481Sgiacomo.travaglini@arm.com::testing::AssertionResult IsEven(int n) {
16713481Sgiacomo.travaglini@arm.com  if ((n % 2) == 0)
16813481Sgiacomo.travaglini@arm.com    return ::testing::AssertionSuccess();
16913481Sgiacomo.travaglini@arm.com  else
17013481Sgiacomo.travaglini@arm.com    return ::testing::AssertionFailure() << n << " is odd";
17113481Sgiacomo.travaglini@arm.com}
17213481Sgiacomo.travaglini@arm.com```
17313481Sgiacomo.travaglini@arm.com
17413481Sgiacomo.travaglini@arm.cominstead of:
17513481Sgiacomo.travaglini@arm.com
17613481Sgiacomo.travaglini@arm.com```
17713481Sgiacomo.travaglini@arm.combool IsEven(int n) {
17813481Sgiacomo.travaglini@arm.com  return (n % 2) == 0;
17913481Sgiacomo.travaglini@arm.com}
18013481Sgiacomo.travaglini@arm.com```
18113481Sgiacomo.travaglini@arm.com
18213481Sgiacomo.travaglini@arm.comthe failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print:
18313481Sgiacomo.travaglini@arm.com
18413481Sgiacomo.travaglini@arm.com<pre>
18513481Sgiacomo.travaglini@arm.comValue of: IsEven(Fib(4))<br>
18613481Sgiacomo.travaglini@arm.comActual: false (*3 is odd*)<br>
18713481Sgiacomo.travaglini@arm.comExpected: true<br>
18813481Sgiacomo.travaglini@arm.com</pre>
18913481Sgiacomo.travaglini@arm.com
19013481Sgiacomo.travaglini@arm.cominstead of a more opaque
19113481Sgiacomo.travaglini@arm.com
19213481Sgiacomo.travaglini@arm.com<pre>
19313481Sgiacomo.travaglini@arm.comValue of: IsEven(Fib(4))<br>
19413481Sgiacomo.travaglini@arm.comActual: false<br>
19513481Sgiacomo.travaglini@arm.comExpected: true<br>
19613481Sgiacomo.travaglini@arm.com</pre>
19713481Sgiacomo.travaglini@arm.com
19813481Sgiacomo.travaglini@arm.comIf you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE`
19913481Sgiacomo.travaglini@arm.comas well, and are fine with making the predicate slower in the success
20013481Sgiacomo.travaglini@arm.comcase, you can supply a success message:
20113481Sgiacomo.travaglini@arm.com
20213481Sgiacomo.travaglini@arm.com```
20313481Sgiacomo.travaglini@arm.com::testing::AssertionResult IsEven(int n) {
20413481Sgiacomo.travaglini@arm.com  if ((n % 2) == 0)
20513481Sgiacomo.travaglini@arm.com    return ::testing::AssertionSuccess() << n << " is even";
20613481Sgiacomo.travaglini@arm.com  else
20713481Sgiacomo.travaglini@arm.com    return ::testing::AssertionFailure() << n << " is odd";
20813481Sgiacomo.travaglini@arm.com}
20913481Sgiacomo.travaglini@arm.com```
21013481Sgiacomo.travaglini@arm.com
21113481Sgiacomo.travaglini@arm.comThen the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print
21213481Sgiacomo.travaglini@arm.com
21313481Sgiacomo.travaglini@arm.com<pre>
21413481Sgiacomo.travaglini@arm.comValue of: IsEven(Fib(6))<br>
21513481Sgiacomo.travaglini@arm.comActual: true (8 is even)<br>
21613481Sgiacomo.travaglini@arm.comExpected: false<br>
21713481Sgiacomo.travaglini@arm.com</pre>
21813481Sgiacomo.travaglini@arm.com
21913481Sgiacomo.travaglini@arm.com_Availability_: Linux, Windows, Mac; since version 1.4.1.
22013481Sgiacomo.travaglini@arm.com
22113481Sgiacomo.travaglini@arm.com### Using a Predicate-Formatter ###
22213481Sgiacomo.travaglini@arm.com
22313481Sgiacomo.travaglini@arm.comIf you find the default message generated by `(ASSERT|EXPECT)_PRED*` and
22413481Sgiacomo.travaglini@arm.com`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your
22513481Sgiacomo.travaglini@arm.compredicate do not support streaming to `ostream`, you can instead use the
22613481Sgiacomo.travaglini@arm.comfollowing _predicate-formatter assertions_ to _fully_ customize how the
22713481Sgiacomo.travaglini@arm.commessage is formatted:
22813481Sgiacomo.travaglini@arm.com
22913481Sgiacomo.travaglini@arm.com| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
23013481Sgiacomo.travaglini@arm.com|:--------------------|:-----------------------|:-------------|
23113481Sgiacomo.travaglini@arm.com| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);`        | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`); | _pred\_format1(val1)_ is successful |
23213481Sgiacomo.travaglini@arm.com| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful |
23313481Sgiacomo.travaglini@arm.com| `...`               | `...`                  | `...`        |
23413481Sgiacomo.travaglini@arm.com
23513481Sgiacomo.travaglini@arm.comThe difference between this and the previous two groups of macros is that instead of
23613481Sgiacomo.travaglini@arm.coma predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_
23713481Sgiacomo.travaglini@arm.com(_pred\_formatn_), which is a function or functor with the signature:
23813481Sgiacomo.travaglini@arm.com
23913481Sgiacomo.travaglini@arm.com`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);`
24013481Sgiacomo.travaglini@arm.com
24113481Sgiacomo.travaglini@arm.comwhere _val1_, _val2_, ..., and _valn_ are the values of the predicate
24213481Sgiacomo.travaglini@arm.comarguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding
24313481Sgiacomo.travaglini@arm.comexpressions as they appear in the source code. The types `T1`, `T2`, ..., and
24413481Sgiacomo.travaglini@arm.com`Tn` can be either value types or reference types. For example, if an
24513481Sgiacomo.travaglini@arm.comargument has type `Foo`, you can declare it as either `Foo` or `const Foo&`,
24613481Sgiacomo.travaglini@arm.comwhichever is appropriate.
24713481Sgiacomo.travaglini@arm.com
24813481Sgiacomo.travaglini@arm.comA predicate-formatter returns a `::testing::AssertionResult` object to indicate
24913481Sgiacomo.travaglini@arm.comwhether the assertion has succeeded or not. The only way to create such an
25013481Sgiacomo.travaglini@arm.comobject is to call one of these factory functions:
25113481Sgiacomo.travaglini@arm.com
25213481Sgiacomo.travaglini@arm.comAs an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`:
25313481Sgiacomo.travaglini@arm.com
25413481Sgiacomo.travaglini@arm.com```
25513481Sgiacomo.travaglini@arm.com// Returns the smallest prime common divisor of m and n,
25613481Sgiacomo.travaglini@arm.com// or 1 when m and n are mutually prime.
25713481Sgiacomo.travaglini@arm.comint SmallestPrimeCommonDivisor(int m, int n) { ... }
25813481Sgiacomo.travaglini@arm.com
25913481Sgiacomo.travaglini@arm.com// A predicate-formatter for asserting that two integers are mutually prime.
26013481Sgiacomo.travaglini@arm.com::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
26113481Sgiacomo.travaglini@arm.com                                               const char* n_expr,
26213481Sgiacomo.travaglini@arm.com                                               int m,
26313481Sgiacomo.travaglini@arm.com                                               int n) {
26413481Sgiacomo.travaglini@arm.com  if (MutuallyPrime(m, n))
26513481Sgiacomo.travaglini@arm.com    return ::testing::AssertionSuccess();
26613481Sgiacomo.travaglini@arm.com
26713481Sgiacomo.travaglini@arm.com  return ::testing::AssertionFailure()
26813481Sgiacomo.travaglini@arm.com      << m_expr << " and " << n_expr << " (" << m << " and " << n
26913481Sgiacomo.travaglini@arm.com      << ") are not mutually prime, " << "as they have a common divisor "
27013481Sgiacomo.travaglini@arm.com      << SmallestPrimeCommonDivisor(m, n);
27113481Sgiacomo.travaglini@arm.com}
27213481Sgiacomo.travaglini@arm.com```
27313481Sgiacomo.travaglini@arm.com
27413481Sgiacomo.travaglini@arm.comWith this predicate-formatter, we can use
27513481Sgiacomo.travaglini@arm.com
27613481Sgiacomo.travaglini@arm.com```
27713481Sgiacomo.travaglini@arm.comEXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c);
27813481Sgiacomo.travaglini@arm.com```
27913481Sgiacomo.travaglini@arm.com
28013481Sgiacomo.travaglini@arm.comto generate the message
28113481Sgiacomo.travaglini@arm.com
28213481Sgiacomo.travaglini@arm.com<pre>
28313481Sgiacomo.travaglini@arm.comb and c (4 and 10) are not mutually prime, as they have a common divisor 2.<br>
28413481Sgiacomo.travaglini@arm.com</pre>
28513481Sgiacomo.travaglini@arm.com
28613481Sgiacomo.travaglini@arm.comAs you may have realized, many of the assertions we introduced earlier are
28713481Sgiacomo.travaglini@arm.comspecial cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are
28813481Sgiacomo.travaglini@arm.comindeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`.
28913481Sgiacomo.travaglini@arm.com
29013481Sgiacomo.travaglini@arm.com_Availability_: Linux, Windows, Mac.
29113481Sgiacomo.travaglini@arm.com
29213481Sgiacomo.travaglini@arm.com
29313481Sgiacomo.travaglini@arm.com## Floating-Point Comparison ##
29413481Sgiacomo.travaglini@arm.com
29513481Sgiacomo.travaglini@arm.comComparing floating-point numbers is tricky. Due to round-off errors, it is
29613481Sgiacomo.travaglini@arm.comvery unlikely that two floating-points will match exactly. Therefore,
29713481Sgiacomo.travaglini@arm.com`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points
29813481Sgiacomo.travaglini@arm.comcan have a wide value range, no single fixed error bound works. It's better to
29913481Sgiacomo.travaglini@arm.comcompare by a fixed relative error bound, except for values close to 0 due to
30013481Sgiacomo.travaglini@arm.comthe loss of precision there.
30113481Sgiacomo.travaglini@arm.com
30213481Sgiacomo.travaglini@arm.comIn general, for floating-point comparison to make sense, the user needs to
30313481Sgiacomo.travaglini@arm.comcarefully choose the error bound. If they don't want or care to, comparing in
30413481Sgiacomo.travaglini@arm.comterms of Units in the Last Place (ULPs) is a good default, and Google Test
30513481Sgiacomo.travaglini@arm.comprovides assertions to do this. Full details about ULPs are quite long; if you
30613481Sgiacomo.travaglini@arm.comwant to learn more, see
30713481Sgiacomo.travaglini@arm.com[this article on float comparison](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm).
30813481Sgiacomo.travaglini@arm.com
30913481Sgiacomo.travaglini@arm.com### Floating-Point Macros ###
31013481Sgiacomo.travaglini@arm.com
31113481Sgiacomo.travaglini@arm.com| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
31213481Sgiacomo.travaglini@arm.com|:--------------------|:-----------------------|:-------------|
31313481Sgiacomo.travaglini@arm.com| `ASSERT_FLOAT_EQ(`_expected, actual_`);`  | `EXPECT_FLOAT_EQ(`_expected, actual_`);` | the two `float` values are almost equal |
31413481Sgiacomo.travaglini@arm.com| `ASSERT_DOUBLE_EQ(`_expected, actual_`);` | `EXPECT_DOUBLE_EQ(`_expected, actual_`);` | the two `double` values are almost equal |
31513481Sgiacomo.travaglini@arm.com
31613481Sgiacomo.travaglini@arm.comBy "almost equal", we mean the two values are within 4 ULP's from each
31713481Sgiacomo.travaglini@arm.comother.
31813481Sgiacomo.travaglini@arm.com
31913481Sgiacomo.travaglini@arm.comThe following assertions allow you to choose the acceptable error bound:
32013481Sgiacomo.travaglini@arm.com
32113481Sgiacomo.travaglini@arm.com| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
32213481Sgiacomo.travaglini@arm.com|:--------------------|:-----------------------|:-------------|
32313481Sgiacomo.travaglini@arm.com| `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 |
32413481Sgiacomo.travaglini@arm.com
32513481Sgiacomo.travaglini@arm.com_Availability_: Linux, Windows, Mac.
32613481Sgiacomo.travaglini@arm.com
32713481Sgiacomo.travaglini@arm.com### Floating-Point Predicate-Format Functions ###
32813481Sgiacomo.travaglini@arm.com
32913481Sgiacomo.travaglini@arm.comSome floating-point operations are useful, but not that often used. In order
33013481Sgiacomo.travaglini@arm.comto avoid an explosion of new macros, we provide them as predicate-format
33113481Sgiacomo.travaglini@arm.comfunctions that can be used in predicate assertion macros (e.g.
33213481Sgiacomo.travaglini@arm.com`EXPECT_PRED_FORMAT2`, etc).
33313481Sgiacomo.travaglini@arm.com
33413481Sgiacomo.travaglini@arm.com```
33513481Sgiacomo.travaglini@arm.comEXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2);
33613481Sgiacomo.travaglini@arm.comEXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2);
33713481Sgiacomo.travaglini@arm.com```
33813481Sgiacomo.travaglini@arm.com
33913481Sgiacomo.travaglini@arm.comVerifies that _val1_ is less than, or almost equal to, _val2_. You can
34013481Sgiacomo.travaglini@arm.comreplace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`.
34113481Sgiacomo.travaglini@arm.com
34213481Sgiacomo.travaglini@arm.com_Availability_: Linux, Windows, Mac.
34313481Sgiacomo.travaglini@arm.com
34413481Sgiacomo.travaglini@arm.com## Windows HRESULT assertions ##
34513481Sgiacomo.travaglini@arm.com
34613481Sgiacomo.travaglini@arm.comThese assertions test for `HRESULT` success or failure.
34713481Sgiacomo.travaglini@arm.com
34813481Sgiacomo.travaglini@arm.com| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
34913481Sgiacomo.travaglini@arm.com|:--------------------|:-----------------------|:-------------|
35013481Sgiacomo.travaglini@arm.com| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` |
35113481Sgiacomo.travaglini@arm.com| `ASSERT_HRESULT_FAILED(`_expression_`);`    | `EXPECT_HRESULT_FAILED(`_expression_`);`    | _expression_ is a failure `HRESULT` |
35213481Sgiacomo.travaglini@arm.com
35313481Sgiacomo.travaglini@arm.comThe generated output contains the human-readable error message
35413481Sgiacomo.travaglini@arm.comassociated with the `HRESULT` code returned by _expression_.
35513481Sgiacomo.travaglini@arm.com
35613481Sgiacomo.travaglini@arm.comYou might use them like this:
35713481Sgiacomo.travaglini@arm.com
35813481Sgiacomo.travaglini@arm.com```
35913481Sgiacomo.travaglini@arm.comCComPtr shell;
36013481Sgiacomo.travaglini@arm.comASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application"));
36113481Sgiacomo.travaglini@arm.comCComVariant empty;
36213481Sgiacomo.travaglini@arm.comASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));
36313481Sgiacomo.travaglini@arm.com```
36413481Sgiacomo.travaglini@arm.com
36513481Sgiacomo.travaglini@arm.com_Availability_: Windows.
36613481Sgiacomo.travaglini@arm.com
36713481Sgiacomo.travaglini@arm.com## Type Assertions ##
36813481Sgiacomo.travaglini@arm.com
36913481Sgiacomo.travaglini@arm.comYou can call the function
37013481Sgiacomo.travaglini@arm.com```
37113481Sgiacomo.travaglini@arm.com::testing::StaticAssertTypeEq<T1, T2>();
37213481Sgiacomo.travaglini@arm.com```
37313481Sgiacomo.travaglini@arm.comto assert that types `T1` and `T2` are the same.  The function does
37413481Sgiacomo.travaglini@arm.comnothing if the assertion is satisfied.  If the types are different,
37513481Sgiacomo.travaglini@arm.comthe function call will fail to compile, and the compiler error message
37613481Sgiacomo.travaglini@arm.comwill likely (depending on the compiler) show you the actual values of
37713481Sgiacomo.travaglini@arm.com`T1` and `T2`.  This is mainly useful inside template code.
37813481Sgiacomo.travaglini@arm.com
37913481Sgiacomo.travaglini@arm.com_Caveat:_ When used inside a member function of a class template or a
38013481Sgiacomo.travaglini@arm.comfunction template, `StaticAssertTypeEq<T1, T2>()` is effective _only if_
38113481Sgiacomo.travaglini@arm.comthe function is instantiated.  For example, given:
38213481Sgiacomo.travaglini@arm.com```
38313481Sgiacomo.travaglini@arm.comtemplate <typename T> class Foo {
38413481Sgiacomo.travaglini@arm.com public:
38513481Sgiacomo.travaglini@arm.com  void Bar() { ::testing::StaticAssertTypeEq<int, T>(); }
38613481Sgiacomo.travaglini@arm.com};
38713481Sgiacomo.travaglini@arm.com```
38813481Sgiacomo.travaglini@arm.comthe code:
38913481Sgiacomo.travaglini@arm.com```
39013481Sgiacomo.travaglini@arm.comvoid Test1() { Foo<bool> foo; }
39113481Sgiacomo.travaglini@arm.com```
39213481Sgiacomo.travaglini@arm.comwill _not_ generate a compiler error, as `Foo<bool>::Bar()` is never
39313481Sgiacomo.travaglini@arm.comactually instantiated.  Instead, you need:
39413481Sgiacomo.travaglini@arm.com```
39513481Sgiacomo.travaglini@arm.comvoid Test2() { Foo<bool> foo; foo.Bar(); }
39613481Sgiacomo.travaglini@arm.com```
39713481Sgiacomo.travaglini@arm.comto cause a compiler error.
39813481Sgiacomo.travaglini@arm.com
39913481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac; since version 1.3.0.
40013481Sgiacomo.travaglini@arm.com
40113481Sgiacomo.travaglini@arm.com## Assertion Placement ##
40213481Sgiacomo.travaglini@arm.com
40313481Sgiacomo.travaglini@arm.comYou can use assertions in any C++ function. In particular, it doesn't
40413481Sgiacomo.travaglini@arm.comhave to be a method of the test fixture class. The one constraint is
40513481Sgiacomo.travaglini@arm.comthat assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`)
40613481Sgiacomo.travaglini@arm.comcan only be used in void-returning functions. This is a consequence of
40713481Sgiacomo.travaglini@arm.comGoogle Test not using exceptions. By placing it in a non-void function
40813481Sgiacomo.travaglini@arm.comyou'll get a confusing compile error like
40913481Sgiacomo.travaglini@arm.com`"error: void value not ignored as it ought to be"`.
41013481Sgiacomo.travaglini@arm.com
41113481Sgiacomo.travaglini@arm.comIf you need to use assertions in a function that returns non-void, one option
41213481Sgiacomo.travaglini@arm.comis to make the function return the value in an out parameter instead. For
41313481Sgiacomo.travaglini@arm.comexample, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You
41413481Sgiacomo.travaglini@arm.comneed to make sure that `*result` contains some sensible value even when the
41513481Sgiacomo.travaglini@arm.comfunction returns prematurely. As the function now returns `void`, you can use
41613481Sgiacomo.travaglini@arm.comany assertion inside of it.
41713481Sgiacomo.travaglini@arm.com
41813481Sgiacomo.travaglini@arm.comIf changing the function's type is not an option, you should just use
41913481Sgiacomo.travaglini@arm.comassertions that generate non-fatal failures, such as `ADD_FAILURE*` and
42013481Sgiacomo.travaglini@arm.com`EXPECT_*`.
42113481Sgiacomo.travaglini@arm.com
42213481Sgiacomo.travaglini@arm.com_Note_: Constructors and destructors are not considered void-returning
42313481Sgiacomo.travaglini@arm.comfunctions, according to the C++ language specification, and so you may not use
42413481Sgiacomo.travaglini@arm.comfatal assertions in them. You'll get a compilation error if you try. A simple
42513481Sgiacomo.travaglini@arm.comworkaround is to transfer the entire body of the constructor or destructor to a
42613481Sgiacomo.travaglini@arm.comprivate void-returning method. However, you should be aware that a fatal
42713481Sgiacomo.travaglini@arm.comassertion failure in a constructor does not terminate the current test, as your
42813481Sgiacomo.travaglini@arm.comintuition might suggest; it merely returns from the constructor early, possibly
42913481Sgiacomo.travaglini@arm.comleaving your object in a partially-constructed state. Likewise, a fatal
43013481Sgiacomo.travaglini@arm.comassertion failure in a destructor may leave your object in a
43113481Sgiacomo.travaglini@arm.compartially-destructed state. Use assertions carefully in these situations!
43213481Sgiacomo.travaglini@arm.com
43313481Sgiacomo.travaglini@arm.com# Teaching Google Test How to Print Your Values #
43413481Sgiacomo.travaglini@arm.com
43513481Sgiacomo.travaglini@arm.comWhen a test assertion such as `EXPECT_EQ` fails, Google Test prints the
43613481Sgiacomo.travaglini@arm.comargument values to help you debug.  It does this using a
43713481Sgiacomo.travaglini@arm.comuser-extensible value printer.
43813481Sgiacomo.travaglini@arm.com
43913481Sgiacomo.travaglini@arm.comThis printer knows how to print built-in C++ types, native arrays, STL
44013481Sgiacomo.travaglini@arm.comcontainers, and any type that supports the `<<` operator.  For other
44113481Sgiacomo.travaglini@arm.comtypes, it prints the raw bytes in the value and hopes that you the
44213481Sgiacomo.travaglini@arm.comuser can figure it out.
44313481Sgiacomo.travaglini@arm.com
44413481Sgiacomo.travaglini@arm.comAs mentioned earlier, the printer is _extensible_.  That means
44513481Sgiacomo.travaglini@arm.comyou can teach it to do a better job at printing your particular type
44613481Sgiacomo.travaglini@arm.comthan to dump the bytes.  To do that, define `<<` for your type:
44713481Sgiacomo.travaglini@arm.com
44813481Sgiacomo.travaglini@arm.com```
44913481Sgiacomo.travaglini@arm.com#include <iostream>
45013481Sgiacomo.travaglini@arm.com
45113481Sgiacomo.travaglini@arm.comnamespace foo {
45213481Sgiacomo.travaglini@arm.com
45313481Sgiacomo.travaglini@arm.comclass Bar { ... };  // We want Google Test to be able to print instances of this.
45413481Sgiacomo.travaglini@arm.com
45513481Sgiacomo.travaglini@arm.com// It's important that the << operator is defined in the SAME
45613481Sgiacomo.travaglini@arm.com// namespace that defines Bar.  C++'s look-up rules rely on that.
45713481Sgiacomo.travaglini@arm.com::std::ostream& operator<<(::std::ostream& os, const Bar& bar) {
45813481Sgiacomo.travaglini@arm.com  return os << bar.DebugString();  // whatever needed to print bar to os
45913481Sgiacomo.travaglini@arm.com}
46013481Sgiacomo.travaglini@arm.com
46113481Sgiacomo.travaglini@arm.com}  // namespace foo
46213481Sgiacomo.travaglini@arm.com```
46313481Sgiacomo.travaglini@arm.com
46413481Sgiacomo.travaglini@arm.comSometimes, this might not be an option: your team may consider it bad
46513481Sgiacomo.travaglini@arm.comstyle to have a `<<` operator for `Bar`, or `Bar` may already have a
46613481Sgiacomo.travaglini@arm.com`<<` operator that doesn't do what you want (and you cannot change
46713481Sgiacomo.travaglini@arm.comit).  If so, you can instead define a `PrintTo()` function like this:
46813481Sgiacomo.travaglini@arm.com
46913481Sgiacomo.travaglini@arm.com```
47013481Sgiacomo.travaglini@arm.com#include <iostream>
47113481Sgiacomo.travaglini@arm.com
47213481Sgiacomo.travaglini@arm.comnamespace foo {
47313481Sgiacomo.travaglini@arm.com
47413481Sgiacomo.travaglini@arm.comclass Bar { ... };
47513481Sgiacomo.travaglini@arm.com
47613481Sgiacomo.travaglini@arm.com// It's important that PrintTo() is defined in the SAME
47713481Sgiacomo.travaglini@arm.com// namespace that defines Bar.  C++'s look-up rules rely on that.
47813481Sgiacomo.travaglini@arm.comvoid PrintTo(const Bar& bar, ::std::ostream* os) {
47913481Sgiacomo.travaglini@arm.com  *os << bar.DebugString();  // whatever needed to print bar to os
48013481Sgiacomo.travaglini@arm.com}
48113481Sgiacomo.travaglini@arm.com
48213481Sgiacomo.travaglini@arm.com}  // namespace foo
48313481Sgiacomo.travaglini@arm.com```
48413481Sgiacomo.travaglini@arm.com
48513481Sgiacomo.travaglini@arm.comIf you have defined both `<<` and `PrintTo()`, the latter will be used
48613481Sgiacomo.travaglini@arm.comwhen Google Test is concerned.  This allows you to customize how the value
48713481Sgiacomo.travaglini@arm.comappears in Google Test's output without affecting code that relies on the
48813481Sgiacomo.travaglini@arm.combehavior of its `<<` operator.
48913481Sgiacomo.travaglini@arm.com
49013481Sgiacomo.travaglini@arm.comIf you want to print a value `x` using Google Test's value printer
49113481Sgiacomo.travaglini@arm.comyourself, just call `::testing::PrintToString(`_x_`)`, which
49213481Sgiacomo.travaglini@arm.comreturns an `std::string`:
49313481Sgiacomo.travaglini@arm.com
49413481Sgiacomo.travaglini@arm.com```
49513481Sgiacomo.travaglini@arm.comvector<pair<Bar, int> > bar_ints = GetBarIntVector();
49613481Sgiacomo.travaglini@arm.com
49713481Sgiacomo.travaglini@arm.comEXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
49813481Sgiacomo.travaglini@arm.com    << "bar_ints = " << ::testing::PrintToString(bar_ints);
49913481Sgiacomo.travaglini@arm.com```
50013481Sgiacomo.travaglini@arm.com
50113481Sgiacomo.travaglini@arm.com# Death Tests #
50213481Sgiacomo.travaglini@arm.com
50313481Sgiacomo.travaglini@arm.comIn many applications, there are assertions that can cause application failure
50413481Sgiacomo.travaglini@arm.comif a condition is not met. These sanity checks, which ensure that the program
50513481Sgiacomo.travaglini@arm.comis in a known good state, are there to fail at the earliest possible time after
50613481Sgiacomo.travaglini@arm.comsome program state is corrupted. If the assertion checks the wrong condition,
50713481Sgiacomo.travaglini@arm.comthen the program may proceed in an erroneous state, which could lead to memory
50813481Sgiacomo.travaglini@arm.comcorruption, security holes, or worse. Hence it is vitally important to test
50913481Sgiacomo.travaglini@arm.comthat such assertion statements work as expected.
51013481Sgiacomo.travaglini@arm.com
51113481Sgiacomo.travaglini@arm.comSince these precondition checks cause the processes to die, we call such tests
51213481Sgiacomo.travaglini@arm.com_death tests_. More generally, any test that checks that a program terminates
51313481Sgiacomo.travaglini@arm.com(except by throwing an exception) in an expected fashion is also a death test.
51413481Sgiacomo.travaglini@arm.com
51513481Sgiacomo.travaglini@arm.comNote that if a piece of code throws an exception, we don't consider it "death"
51613481Sgiacomo.travaglini@arm.comfor the purpose of death tests, as the caller of the code could catch the exception
51713481Sgiacomo.travaglini@arm.comand avoid the crash. If you want to verify exceptions thrown by your code,
51813481Sgiacomo.travaglini@arm.comsee [Exception Assertions](#exception-assertions).
51913481Sgiacomo.travaglini@arm.com
52013481Sgiacomo.travaglini@arm.comIf you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#catching-failures).
52113481Sgiacomo.travaglini@arm.com
52213481Sgiacomo.travaglini@arm.com## How to Write a Death Test ##
52313481Sgiacomo.travaglini@arm.com
52413481Sgiacomo.travaglini@arm.comGoogle Test has the following macros to support death tests:
52513481Sgiacomo.travaglini@arm.com
52613481Sgiacomo.travaglini@arm.com| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
52713481Sgiacomo.travaglini@arm.com|:--------------------|:-----------------------|:-------------|
52813481Sgiacomo.travaglini@arm.com| `ASSERT_DEATH(`_statement, regex_`); | `EXPECT_DEATH(`_statement, regex_`); | _statement_ crashes with the given error |
52913481Sgiacomo.travaglini@arm.com| `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 |
53013481Sgiacomo.travaglini@arm.com| `ASSERT_EXIT(`_statement, predicate, regex_`); | `EXPECT_EXIT(`_statement, predicate, regex_`); |_statement_ exits with the given error and its exit code matches _predicate_ |
53113481Sgiacomo.travaglini@arm.com
53213481Sgiacomo.travaglini@arm.comwhere _statement_ is a statement that is expected to cause the process to
53313481Sgiacomo.travaglini@arm.comdie, _predicate_ is a function or function object that evaluates an integer
53413481Sgiacomo.travaglini@arm.comexit status, and _regex_ is a regular expression that the stderr output of
53513481Sgiacomo.travaglini@arm.com_statement_ is expected to match. Note that _statement_ can be _any valid
53613481Sgiacomo.travaglini@arm.comstatement_ (including _compound statement_) and doesn't have to be an
53713481Sgiacomo.travaglini@arm.comexpression.
53813481Sgiacomo.travaglini@arm.com
53913481Sgiacomo.travaglini@arm.comAs usual, the `ASSERT` variants abort the current test function, while the
54013481Sgiacomo.travaglini@arm.com`EXPECT` variants do not.
54113481Sgiacomo.travaglini@arm.com
54213481Sgiacomo.travaglini@arm.com**Note:** We use the word "crash" here to mean that the process
54313481Sgiacomo.travaglini@arm.comterminates with a _non-zero_ exit status code.  There are two
54413481Sgiacomo.travaglini@arm.compossibilities: either the process has called `exit()` or `_exit()`
54513481Sgiacomo.travaglini@arm.comwith a non-zero value, or it may be killed by a signal.
54613481Sgiacomo.travaglini@arm.com
54713481Sgiacomo.travaglini@arm.comThis means that if _statement_ terminates the process with a 0 exit
54813481Sgiacomo.travaglini@arm.comcode, it is _not_ considered a crash by `EXPECT_DEATH`.  Use
54913481Sgiacomo.travaglini@arm.com`EXPECT_EXIT` instead if this is the case, or if you want to restrict
55013481Sgiacomo.travaglini@arm.comthe exit code more precisely.
55113481Sgiacomo.travaglini@arm.com
55213481Sgiacomo.travaglini@arm.comA predicate here must accept an `int` and return a `bool`. The death test
55313481Sgiacomo.travaglini@arm.comsucceeds only if the predicate returns `true`. Google Test defines a few
55413481Sgiacomo.travaglini@arm.compredicates that handle the most common cases:
55513481Sgiacomo.travaglini@arm.com
55613481Sgiacomo.travaglini@arm.com```
55713481Sgiacomo.travaglini@arm.com::testing::ExitedWithCode(exit_code)
55813481Sgiacomo.travaglini@arm.com```
55913481Sgiacomo.travaglini@arm.com
56013481Sgiacomo.travaglini@arm.comThis expression is `true` if the program exited normally with the given exit
56113481Sgiacomo.travaglini@arm.comcode.
56213481Sgiacomo.travaglini@arm.com
56313481Sgiacomo.travaglini@arm.com```
56413481Sgiacomo.travaglini@arm.com::testing::KilledBySignal(signal_number)  // Not available on Windows.
56513481Sgiacomo.travaglini@arm.com```
56613481Sgiacomo.travaglini@arm.com
56713481Sgiacomo.travaglini@arm.comThis expression is `true` if the program was killed by the given signal.
56813481Sgiacomo.travaglini@arm.com
56913481Sgiacomo.travaglini@arm.comThe `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate
57013481Sgiacomo.travaglini@arm.comthat verifies the process' exit code is non-zero.
57113481Sgiacomo.travaglini@arm.com
57213481Sgiacomo.travaglini@arm.comNote that a death test only cares about three things:
57313481Sgiacomo.travaglini@arm.com
57413481Sgiacomo.travaglini@arm.com  1. does _statement_ abort or exit the process?
57513481Sgiacomo.travaglini@arm.com  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
57613481Sgiacomo.travaglini@arm.com  1. does the stderr output match _regex_?
57713481Sgiacomo.travaglini@arm.com
57813481Sgiacomo.travaglini@arm.comIn 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.
57913481Sgiacomo.travaglini@arm.com
58013481Sgiacomo.travaglini@arm.comTo write a death test, simply use one of the above macros inside your test
58113481Sgiacomo.travaglini@arm.comfunction. For example,
58213481Sgiacomo.travaglini@arm.com
58313481Sgiacomo.travaglini@arm.com```
58413481Sgiacomo.travaglini@arm.comTEST(MyDeathTest, Foo) {
58513481Sgiacomo.travaglini@arm.com  // This death test uses a compound statement.
58613481Sgiacomo.travaglini@arm.com  ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()");
58713481Sgiacomo.travaglini@arm.com}
58813481Sgiacomo.travaglini@arm.comTEST(MyDeathTest, NormalExit) {
58913481Sgiacomo.travaglini@arm.com  EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success");
59013481Sgiacomo.travaglini@arm.com}
59113481Sgiacomo.travaglini@arm.comTEST(MyDeathTest, KillMyself) {
59213481Sgiacomo.travaglini@arm.com  EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal");
59313481Sgiacomo.travaglini@arm.com}
59413481Sgiacomo.travaglini@arm.com```
59513481Sgiacomo.travaglini@arm.com
59613481Sgiacomo.travaglini@arm.comverifies that:
59713481Sgiacomo.travaglini@arm.com
59813481Sgiacomo.travaglini@arm.com  * calling `Foo(5)` causes the process to die with the given error message,
59913481Sgiacomo.travaglini@arm.com  * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and
60013481Sgiacomo.travaglini@arm.com  * calling `KillMyself()` kills the process with signal `SIGKILL`.
60113481Sgiacomo.travaglini@arm.com
60213481Sgiacomo.travaglini@arm.comThe test function body may contain other assertions and statements as well, if
60313481Sgiacomo.travaglini@arm.comnecessary.
60413481Sgiacomo.travaglini@arm.com
60513481Sgiacomo.travaglini@arm.com_Important:_ We strongly recommend you to follow the convention of naming your
60613481Sgiacomo.travaglini@arm.comtest case (not test) `*DeathTest` when it contains a death test, as
60713481Sgiacomo.travaglini@arm.comdemonstrated in the above example. The `Death Tests And Threads` section below
60813481Sgiacomo.travaglini@arm.comexplains why.
60913481Sgiacomo.travaglini@arm.com
61013481Sgiacomo.travaglini@arm.comIf a test fixture class is shared by normal tests and death tests, you
61113481Sgiacomo.travaglini@arm.comcan use typedef to introduce an alias for the fixture class and avoid
61213481Sgiacomo.travaglini@arm.comduplicating its code:
61313481Sgiacomo.travaglini@arm.com```
61413481Sgiacomo.travaglini@arm.comclass FooTest : public ::testing::Test { ... };
61513481Sgiacomo.travaglini@arm.com
61613481Sgiacomo.travaglini@arm.comtypedef FooTest FooDeathTest;
61713481Sgiacomo.travaglini@arm.com
61813481Sgiacomo.travaglini@arm.comTEST_F(FooTest, DoesThis) {
61913481Sgiacomo.travaglini@arm.com  // normal test
62013481Sgiacomo.travaglini@arm.com}
62113481Sgiacomo.travaglini@arm.com
62213481Sgiacomo.travaglini@arm.comTEST_F(FooDeathTest, DoesThat) {
62313481Sgiacomo.travaglini@arm.com  // death test
62413481Sgiacomo.travaglini@arm.com}
62513481Sgiacomo.travaglini@arm.com```
62613481Sgiacomo.travaglini@arm.com
62713481Sgiacomo.travaglini@arm.com_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.
62813481Sgiacomo.travaglini@arm.com
62913481Sgiacomo.travaglini@arm.com## Regular Expression Syntax ##
63013481Sgiacomo.travaglini@arm.com
63113481Sgiacomo.travaglini@arm.comOn POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the
63213481Sgiacomo.travaglini@arm.com[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
63313481Sgiacomo.travaglini@arm.comsyntax 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).
63413481Sgiacomo.travaglini@arm.com
63513481Sgiacomo.travaglini@arm.comOn Windows, Google Test uses its own simple regular expression
63613481Sgiacomo.travaglini@arm.comimplementation. It lacks many features you can find in POSIX extended
63713481Sgiacomo.travaglini@arm.comregular expressions.  For example, we don't support union (`"x|y"`),
63813481Sgiacomo.travaglini@arm.comgrouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count
63913481Sgiacomo.travaglini@arm.com(`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a
64013481Sgiacomo.travaglini@arm.comliteral character, period (`.`), or a single `\\` escape sequence; `x`
64113481Sgiacomo.travaglini@arm.comand `y` denote regular expressions.):
64213481Sgiacomo.travaglini@arm.com
64313481Sgiacomo.travaglini@arm.com| `c` | matches any literal character `c` |
64413481Sgiacomo.travaglini@arm.com|:----|:----------------------------------|
64513481Sgiacomo.travaglini@arm.com| `\\d` | matches any decimal digit         |
64613481Sgiacomo.travaglini@arm.com| `\\D` | matches any character that's not a decimal digit |
64713481Sgiacomo.travaglini@arm.com| `\\f` | matches `\f`                      |
64813481Sgiacomo.travaglini@arm.com| `\\n` | matches `\n`                      |
64913481Sgiacomo.travaglini@arm.com| `\\r` | matches `\r`                      |
65013481Sgiacomo.travaglini@arm.com| `\\s` | matches any ASCII whitespace, including `\n` |
65113481Sgiacomo.travaglini@arm.com| `\\S` | matches any character that's not a whitespace |
65213481Sgiacomo.travaglini@arm.com| `\\t` | matches `\t`                      |
65313481Sgiacomo.travaglini@arm.com| `\\v` | matches `\v`                      |
65413481Sgiacomo.travaglini@arm.com| `\\w` | matches any letter, `_`, or decimal digit |
65513481Sgiacomo.travaglini@arm.com| `\\W` | matches any character that `\\w` doesn't match |
65613481Sgiacomo.travaglini@arm.com| `\\c` | matches any literal character `c`, which must be a punctuation |
65713481Sgiacomo.travaglini@arm.com| `\\.` | matches the `.` character         |
65813481Sgiacomo.travaglini@arm.com| `.` | matches any single character except `\n` |
65913481Sgiacomo.travaglini@arm.com| `A?` | matches 0 or 1 occurrences of `A` |
66013481Sgiacomo.travaglini@arm.com| `A*` | matches 0 or many occurrences of `A` |
66113481Sgiacomo.travaglini@arm.com| `A+` | matches 1 or many occurrences of `A` |
66213481Sgiacomo.travaglini@arm.com| `^` | matches the beginning of a string (not that of each line) |
66313481Sgiacomo.travaglini@arm.com| `$` | matches the end of a string (not that of each line) |
66413481Sgiacomo.travaglini@arm.com| `xy` | matches `x` followed by `y`       |
66513481Sgiacomo.travaglini@arm.com
66613481Sgiacomo.travaglini@arm.comTo help you determine which capability is available on your system,
66713481Sgiacomo.travaglini@arm.comGoogle Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX
66813481Sgiacomo.travaglini@arm.comextended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses
66913481Sgiacomo.travaglini@arm.comthe simple version.  If you want your death tests to work in both
67013481Sgiacomo.travaglini@arm.comcases, you can either `#if` on these macros or use the more limited
67113481Sgiacomo.travaglini@arm.comsyntax only.
67213481Sgiacomo.travaglini@arm.com
67313481Sgiacomo.travaglini@arm.com## How It Works ##
67413481Sgiacomo.travaglini@arm.com
67513481Sgiacomo.travaglini@arm.comUnder the hood, `ASSERT_EXIT()` spawns a new process and executes the
67613481Sgiacomo.travaglini@arm.comdeath test statement in that process. The details of of how precisely
67713481Sgiacomo.travaglini@arm.comthat happens depend on the platform and the variable
67813481Sgiacomo.travaglini@arm.com`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the
67913481Sgiacomo.travaglini@arm.comcommand-line flag `--gtest_death_test_style`).
68013481Sgiacomo.travaglini@arm.com
68113481Sgiacomo.travaglini@arm.com  * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which:
68213481Sgiacomo.travaglini@arm.com    * If the variable's value is `"fast"`, the death test statement is immediately executed.
68313481Sgiacomo.travaglini@arm.com    * 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.
68413481Sgiacomo.travaglini@arm.com  * 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.
68513481Sgiacomo.travaglini@arm.com
68613481Sgiacomo.travaglini@arm.comOther values for the variable are illegal and will cause the death test to
68713481Sgiacomo.travaglini@arm.comfail. Currently, the flag's default value is `"fast"`. However, we reserve the
68813481Sgiacomo.travaglini@arm.comright to change it in the future. Therefore, your tests should not depend on
68913481Sgiacomo.travaglini@arm.comthis.
69013481Sgiacomo.travaglini@arm.com
69113481Sgiacomo.travaglini@arm.comIn either case, the parent process waits for the child process to complete, and checks that
69213481Sgiacomo.travaglini@arm.com
69313481Sgiacomo.travaglini@arm.com  1. the child's exit status satisfies the predicate, and
69413481Sgiacomo.travaglini@arm.com  1. the child's stderr matches the regular expression.
69513481Sgiacomo.travaglini@arm.com
69613481Sgiacomo.travaglini@arm.comIf the death test statement runs to completion without dying, the child
69713481Sgiacomo.travaglini@arm.comprocess will nonetheless terminate, and the assertion fails.
69813481Sgiacomo.travaglini@arm.com
69913481Sgiacomo.travaglini@arm.com## Death Tests And Threads ##
70013481Sgiacomo.travaglini@arm.com
70113481Sgiacomo.travaglini@arm.comThe reason for the two death test styles has to do with thread safety. Due to
70213481Sgiacomo.travaglini@arm.comwell-known problems with forking in the presence of threads, death tests should
70313481Sgiacomo.travaglini@arm.combe run in a single-threaded context. Sometimes, however, it isn't feasible to
70413481Sgiacomo.travaglini@arm.comarrange that kind of environment. For example, statically-initialized modules
70513481Sgiacomo.travaglini@arm.commay start threads before main is ever reached. Once threads have been created,
70613481Sgiacomo.travaglini@arm.comit may be difficult or impossible to clean them up.
70713481Sgiacomo.travaglini@arm.com
70813481Sgiacomo.travaglini@arm.comGoogle Test has three features intended to raise awareness of threading issues.
70913481Sgiacomo.travaglini@arm.com
71013481Sgiacomo.travaglini@arm.com  1. A warning is emitted if multiple threads are running when a death test is encountered.
71113481Sgiacomo.travaglini@arm.com  1. Test cases with a name ending in "DeathTest" are run before all other tests.
71213481Sgiacomo.travaglini@arm.com  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.
71313481Sgiacomo.travaglini@arm.com
71413481Sgiacomo.travaglini@arm.comIt's perfectly fine to create threads inside a death test statement; they are
71513481Sgiacomo.travaglini@arm.comexecuted in a separate process and cannot affect the parent.
71613481Sgiacomo.travaglini@arm.com
71713481Sgiacomo.travaglini@arm.com## Death Test Styles ##
71813481Sgiacomo.travaglini@arm.com
71913481Sgiacomo.travaglini@arm.comThe "threadsafe" death test style was introduced in order to help mitigate the
72013481Sgiacomo.travaglini@arm.comrisks of testing in a possibly multithreaded environment. It trades increased
72113481Sgiacomo.travaglini@arm.comtest execution time (potentially dramatically so) for improved thread safety.
72213481Sgiacomo.travaglini@arm.comWe suggest using the faster, default "fast" style unless your test has specific
72313481Sgiacomo.travaglini@arm.comproblems with it.
72413481Sgiacomo.travaglini@arm.com
72513481Sgiacomo.travaglini@arm.comYou can choose a particular style of death tests by setting the flag
72613481Sgiacomo.travaglini@arm.comprogrammatically:
72713481Sgiacomo.travaglini@arm.com
72813481Sgiacomo.travaglini@arm.com```
72913481Sgiacomo.travaglini@arm.com::testing::FLAGS_gtest_death_test_style = "threadsafe";
73013481Sgiacomo.travaglini@arm.com```
73113481Sgiacomo.travaglini@arm.com
73213481Sgiacomo.travaglini@arm.comYou can do this in `main()` to set the style for all death tests in the
73313481Sgiacomo.travaglini@arm.combinary, or in individual tests. Recall that flags are saved before running each
73413481Sgiacomo.travaglini@arm.comtest and restored afterwards, so you need not do that yourself. For example:
73513481Sgiacomo.travaglini@arm.com
73613481Sgiacomo.travaglini@arm.com```
73713481Sgiacomo.travaglini@arm.comTEST(MyDeathTest, TestOne) {
73813481Sgiacomo.travaglini@arm.com  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
73913481Sgiacomo.travaglini@arm.com  // This test is run in the "threadsafe" style:
74013481Sgiacomo.travaglini@arm.com  ASSERT_DEATH(ThisShouldDie(), "");
74113481Sgiacomo.travaglini@arm.com}
74213481Sgiacomo.travaglini@arm.com
74313481Sgiacomo.travaglini@arm.comTEST(MyDeathTest, TestTwo) {
74413481Sgiacomo.travaglini@arm.com  // This test is run in the "fast" style:
74513481Sgiacomo.travaglini@arm.com  ASSERT_DEATH(ThisShouldDie(), "");
74613481Sgiacomo.travaglini@arm.com}
74713481Sgiacomo.travaglini@arm.com
74813481Sgiacomo.travaglini@arm.comint main(int argc, char** argv) {
74913481Sgiacomo.travaglini@arm.com  ::testing::InitGoogleTest(&argc, argv);
75013481Sgiacomo.travaglini@arm.com  ::testing::FLAGS_gtest_death_test_style = "fast";
75113481Sgiacomo.travaglini@arm.com  return RUN_ALL_TESTS();
75213481Sgiacomo.travaglini@arm.com}
75313481Sgiacomo.travaglini@arm.com```
75413481Sgiacomo.travaglini@arm.com
75513481Sgiacomo.travaglini@arm.com## Caveats ##
75613481Sgiacomo.travaglini@arm.com
75713481Sgiacomo.travaglini@arm.comThe _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement.
75813481Sgiacomo.travaglini@arm.comIf it leaves the current function via a `return` statement or by throwing an exception,
75913481Sgiacomo.travaglini@arm.comthe death test is considered to have failed.  Some Google Test macros may return
76013481Sgiacomo.travaglini@arm.comfrom the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_.
76113481Sgiacomo.travaglini@arm.com
76213481Sgiacomo.travaglini@arm.comSince _statement_ runs in the child process, any in-memory side effect (e.g.
76313481Sgiacomo.travaglini@arm.commodifying a variable, releasing memory, etc) it causes will _not_ be observable
76413481Sgiacomo.travaglini@arm.comin the parent process. In particular, if you release memory in a death test,
76513481Sgiacomo.travaglini@arm.comyour program will fail the heap check as the parent process will never see the
76613481Sgiacomo.travaglini@arm.commemory reclaimed. To solve this problem, you can
76713481Sgiacomo.travaglini@arm.com
76813481Sgiacomo.travaglini@arm.com  1. try not to free memory in a death test;
76913481Sgiacomo.travaglini@arm.com  1. free the memory again in the parent process; or
77013481Sgiacomo.travaglini@arm.com  1. do not use the heap checker in your program.
77113481Sgiacomo.travaglini@arm.com
77213481Sgiacomo.travaglini@arm.comDue to an implementation detail, you cannot place multiple death test
77313481Sgiacomo.travaglini@arm.comassertions on the same line; otherwise, compilation will fail with an unobvious
77413481Sgiacomo.travaglini@arm.comerror message.
77513481Sgiacomo.travaglini@arm.com
77613481Sgiacomo.travaglini@arm.comDespite the improved thread safety afforded by the "threadsafe" style of death
77713481Sgiacomo.travaglini@arm.comtest, thread problems such as deadlock are still possible in the presence of
77813481Sgiacomo.travaglini@arm.comhandlers registered with `pthread_atfork(3)`.
77913481Sgiacomo.travaglini@arm.com
78013481Sgiacomo.travaglini@arm.com# Using Assertions in Sub-routines #
78113481Sgiacomo.travaglini@arm.com
78213481Sgiacomo.travaglini@arm.com## Adding Traces to Assertions ##
78313481Sgiacomo.travaglini@arm.com
78413481Sgiacomo.travaglini@arm.comIf a test sub-routine is called from several places, when an assertion
78513481Sgiacomo.travaglini@arm.cominside it fails, it can be hard to tell which invocation of the
78613481Sgiacomo.travaglini@arm.comsub-routine the failure is from.  You can alleviate this problem using
78713481Sgiacomo.travaglini@arm.comextra logging or custom failure messages, but that usually clutters up
78813481Sgiacomo.travaglini@arm.comyour tests. A better solution is to use the `SCOPED_TRACE` macro:
78913481Sgiacomo.travaglini@arm.com
79013481Sgiacomo.travaglini@arm.com| `SCOPED_TRACE(`_message_`);` |
79113481Sgiacomo.travaglini@arm.com|:-----------------------------|
79213481Sgiacomo.travaglini@arm.com
79313481Sgiacomo.travaglini@arm.comwhere _message_ can be anything streamable to `std::ostream`. This
79413481Sgiacomo.travaglini@arm.commacro will cause the current file name, line number, and the given
79513481Sgiacomo.travaglini@arm.commessage to be added in every failure message. The effect will be
79613481Sgiacomo.travaglini@arm.comundone when the control leaves the current lexical scope.
79713481Sgiacomo.travaglini@arm.com
79813481Sgiacomo.travaglini@arm.comFor example,
79913481Sgiacomo.travaglini@arm.com
80013481Sgiacomo.travaglini@arm.com```
80113481Sgiacomo.travaglini@arm.com10: void Sub1(int n) {
80213481Sgiacomo.travaglini@arm.com11:   EXPECT_EQ(1, Bar(n));
80313481Sgiacomo.travaglini@arm.com12:   EXPECT_EQ(2, Bar(n + 1));
80413481Sgiacomo.travaglini@arm.com13: }
80513481Sgiacomo.travaglini@arm.com14:
80613481Sgiacomo.travaglini@arm.com15: TEST(FooTest, Bar) {
80713481Sgiacomo.travaglini@arm.com16:   {
80813481Sgiacomo.travaglini@arm.com17:     SCOPED_TRACE("A");  // This trace point will be included in
80913481Sgiacomo.travaglini@arm.com18:                         // every failure in this scope.
81013481Sgiacomo.travaglini@arm.com19:     Sub1(1);
81113481Sgiacomo.travaglini@arm.com20:   }
81213481Sgiacomo.travaglini@arm.com21:   // Now it won't.
81313481Sgiacomo.travaglini@arm.com22:   Sub1(9);
81413481Sgiacomo.travaglini@arm.com23: }
81513481Sgiacomo.travaglini@arm.com```
81613481Sgiacomo.travaglini@arm.com
81713481Sgiacomo.travaglini@arm.comcould result in messages like these:
81813481Sgiacomo.travaglini@arm.com
81913481Sgiacomo.travaglini@arm.com```
82013481Sgiacomo.travaglini@arm.compath/to/foo_test.cc:11: Failure
82113481Sgiacomo.travaglini@arm.comValue of: Bar(n)
82213481Sgiacomo.travaglini@arm.comExpected: 1
82313481Sgiacomo.travaglini@arm.com  Actual: 2
82413481Sgiacomo.travaglini@arm.com   Trace:
82513481Sgiacomo.travaglini@arm.compath/to/foo_test.cc:17: A
82613481Sgiacomo.travaglini@arm.com
82713481Sgiacomo.travaglini@arm.compath/to/foo_test.cc:12: Failure
82813481Sgiacomo.travaglini@arm.comValue of: Bar(n + 1)
82913481Sgiacomo.travaglini@arm.comExpected: 2
83013481Sgiacomo.travaglini@arm.com  Actual: 3
83113481Sgiacomo.travaglini@arm.com```
83213481Sgiacomo.travaglini@arm.com
83313481Sgiacomo.travaglini@arm.comWithout the trace, it would've been difficult to know which invocation
83413481Sgiacomo.travaglini@arm.comof `Sub1()` the two failures come from respectively. (You could add an
83513481Sgiacomo.travaglini@arm.comextra message to each assertion in `Sub1()` to indicate the value of
83613481Sgiacomo.travaglini@arm.com`n`, but that's tedious.)
83713481Sgiacomo.travaglini@arm.com
83813481Sgiacomo.travaglini@arm.comSome tips on using `SCOPED_TRACE`:
83913481Sgiacomo.travaglini@arm.com
84013481Sgiacomo.travaglini@arm.com  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.
84113481Sgiacomo.travaglini@arm.com  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.
84213481Sgiacomo.travaglini@arm.com  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 `""`.
84313481Sgiacomo.travaglini@arm.com  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.
84413481Sgiacomo.travaglini@arm.com  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!
84513481Sgiacomo.travaglini@arm.com
84613481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.
84713481Sgiacomo.travaglini@arm.com
84813481Sgiacomo.travaglini@arm.com## Propagating Fatal Failures ##
84913481Sgiacomo.travaglini@arm.com
85013481Sgiacomo.travaglini@arm.comA common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that
85113481Sgiacomo.travaglini@arm.comwhen they fail they only abort the _current function_, not the entire test. For
85213481Sgiacomo.travaglini@arm.comexample, the following test will segfault:
85313481Sgiacomo.travaglini@arm.com```
85413481Sgiacomo.travaglini@arm.comvoid Subroutine() {
85513481Sgiacomo.travaglini@arm.com  // Generates a fatal failure and aborts the current function.
85613481Sgiacomo.travaglini@arm.com  ASSERT_EQ(1, 2);
85713481Sgiacomo.travaglini@arm.com  // The following won't be executed.
85813481Sgiacomo.travaglini@arm.com  ...
85913481Sgiacomo.travaglini@arm.com}
86013481Sgiacomo.travaglini@arm.com
86113481Sgiacomo.travaglini@arm.comTEST(FooTest, Bar) {
86213481Sgiacomo.travaglini@arm.com  Subroutine();
86313481Sgiacomo.travaglini@arm.com  // The intended behavior is for the fatal failure
86413481Sgiacomo.travaglini@arm.com  // in Subroutine() to abort the entire test.
86513481Sgiacomo.travaglini@arm.com  // The actual behavior: the function goes on after Subroutine() returns.
86613481Sgiacomo.travaglini@arm.com  int* p = NULL;
86713481Sgiacomo.travaglini@arm.com  *p = 3; // Segfault!
86813481Sgiacomo.travaglini@arm.com}
86913481Sgiacomo.travaglini@arm.com```
87013481Sgiacomo.travaglini@arm.com
87113481Sgiacomo.travaglini@arm.comSince we don't use exceptions, it is technically impossible to
87213481Sgiacomo.travaglini@arm.comimplement the intended behavior here.  To alleviate this, Google Test
87313481Sgiacomo.travaglini@arm.comprovides two solutions.  You could use either the
87413481Sgiacomo.travaglini@arm.com`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
87513481Sgiacomo.travaglini@arm.com`HasFatalFailure()` function.  They are described in the following two
87613481Sgiacomo.travaglini@arm.comsubsections.
87713481Sgiacomo.travaglini@arm.com
87813481Sgiacomo.travaglini@arm.com### Asserting on Subroutines ###
87913481Sgiacomo.travaglini@arm.com
88013481Sgiacomo.travaglini@arm.comAs shown above, if your test calls a subroutine that has an `ASSERT_*`
88113481Sgiacomo.travaglini@arm.comfailure in it, the test will continue after the subroutine
88213481Sgiacomo.travaglini@arm.comreturns. This may not be what you want.
88313481Sgiacomo.travaglini@arm.com
88413481Sgiacomo.travaglini@arm.comOften people want fatal failures to propagate like exceptions.  For
88513481Sgiacomo.travaglini@arm.comthat Google Test offers the following macros:
88613481Sgiacomo.travaglini@arm.com
88713481Sgiacomo.travaglini@arm.com| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
88813481Sgiacomo.travaglini@arm.com|:--------------------|:-----------------------|:-------------|
88913481Sgiacomo.travaglini@arm.com| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. |
89013481Sgiacomo.travaglini@arm.com
89113481Sgiacomo.travaglini@arm.comOnly failures in the thread that executes the assertion are checked to
89213481Sgiacomo.travaglini@arm.comdetermine the result of this type of assertions.  If _statement_
89313481Sgiacomo.travaglini@arm.comcreates new threads, failures in these threads are ignored.
89413481Sgiacomo.travaglini@arm.com
89513481Sgiacomo.travaglini@arm.comExamples:
89613481Sgiacomo.travaglini@arm.com
89713481Sgiacomo.travaglini@arm.com```
89813481Sgiacomo.travaglini@arm.comASSERT_NO_FATAL_FAILURE(Foo());
89913481Sgiacomo.travaglini@arm.com
90013481Sgiacomo.travaglini@arm.comint i;
90113481Sgiacomo.travaglini@arm.comEXPECT_NO_FATAL_FAILURE({
90213481Sgiacomo.travaglini@arm.com  i = Bar();
90313481Sgiacomo.travaglini@arm.com});
90413481Sgiacomo.travaglini@arm.com```
90513481Sgiacomo.travaglini@arm.com
90613481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac. Assertions from multiple threads
90713481Sgiacomo.travaglini@arm.comare currently not supported.
90813481Sgiacomo.travaglini@arm.com
90913481Sgiacomo.travaglini@arm.com### Checking for Failures in the Current Test ###
91013481Sgiacomo.travaglini@arm.com
91113481Sgiacomo.travaglini@arm.com`HasFatalFailure()` in the `::testing::Test` class returns `true` if an
91213481Sgiacomo.travaglini@arm.comassertion in the current test has suffered a fatal failure. This
91313481Sgiacomo.travaglini@arm.comallows functions to catch fatal failures in a sub-routine and return
91413481Sgiacomo.travaglini@arm.comearly.
91513481Sgiacomo.travaglini@arm.com
91613481Sgiacomo.travaglini@arm.com```
91713481Sgiacomo.travaglini@arm.comclass Test {
91813481Sgiacomo.travaglini@arm.com public:
91913481Sgiacomo.travaglini@arm.com  ...
92013481Sgiacomo.travaglini@arm.com  static bool HasFatalFailure();
92113481Sgiacomo.travaglini@arm.com};
92213481Sgiacomo.travaglini@arm.com```
92313481Sgiacomo.travaglini@arm.com
92413481Sgiacomo.travaglini@arm.comThe typical usage, which basically simulates the behavior of a thrown
92513481Sgiacomo.travaglini@arm.comexception, is:
92613481Sgiacomo.travaglini@arm.com
92713481Sgiacomo.travaglini@arm.com```
92813481Sgiacomo.travaglini@arm.comTEST(FooTest, Bar) {
92913481Sgiacomo.travaglini@arm.com  Subroutine();
93013481Sgiacomo.travaglini@arm.com  // Aborts if Subroutine() had a fatal failure.
93113481Sgiacomo.travaglini@arm.com  if (HasFatalFailure())
93213481Sgiacomo.travaglini@arm.com    return;
93313481Sgiacomo.travaglini@arm.com  // The following won't be executed.
93413481Sgiacomo.travaglini@arm.com  ...
93513481Sgiacomo.travaglini@arm.com}
93613481Sgiacomo.travaglini@arm.com```
93713481Sgiacomo.travaglini@arm.com
93813481Sgiacomo.travaglini@arm.comIf `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test
93913481Sgiacomo.travaglini@arm.comfixture, you must add the `::testing::Test::` prefix, as in:
94013481Sgiacomo.travaglini@arm.com
94113481Sgiacomo.travaglini@arm.com```
94213481Sgiacomo.travaglini@arm.comif (::testing::Test::HasFatalFailure())
94313481Sgiacomo.travaglini@arm.com  return;
94413481Sgiacomo.travaglini@arm.com```
94513481Sgiacomo.travaglini@arm.com
94613481Sgiacomo.travaglini@arm.comSimilarly, `HasNonfatalFailure()` returns `true` if the current test
94713481Sgiacomo.travaglini@arm.comhas at least one non-fatal failure, and `HasFailure()` returns `true`
94813481Sgiacomo.travaglini@arm.comif the current test has at least one failure of either kind.
94913481Sgiacomo.travaglini@arm.com
95013481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.  `HasNonfatalFailure()` and
95113481Sgiacomo.travaglini@arm.com`HasFailure()` are available since version 1.4.0.
95213481Sgiacomo.travaglini@arm.com
95313481Sgiacomo.travaglini@arm.com# Logging Additional Information #
95413481Sgiacomo.travaglini@arm.com
95513481Sgiacomo.travaglini@arm.comIn your test code, you can call `RecordProperty("key", value)` to log
95613481Sgiacomo.travaglini@arm.comadditional 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
95713481Sgiacomo.travaglini@arm.comif you specify one. For example, the test
95813481Sgiacomo.travaglini@arm.com
95913481Sgiacomo.travaglini@arm.com```
96013481Sgiacomo.travaglini@arm.comTEST_F(WidgetUsageTest, MinAndMaxWidgets) {
96113481Sgiacomo.travaglini@arm.com  RecordProperty("MaximumWidgets", ComputeMaxUsage());
96213481Sgiacomo.travaglini@arm.com  RecordProperty("MinimumWidgets", ComputeMinUsage());
96313481Sgiacomo.travaglini@arm.com}
96413481Sgiacomo.travaglini@arm.com```
96513481Sgiacomo.travaglini@arm.com
96613481Sgiacomo.travaglini@arm.comwill output XML like this:
96713481Sgiacomo.travaglini@arm.com
96813481Sgiacomo.travaglini@arm.com```
96913481Sgiacomo.travaglini@arm.com...
97013481Sgiacomo.travaglini@arm.com  <testcase name="MinAndMaxWidgets" status="run" time="6" classname="WidgetUsageTest"
97113481Sgiacomo.travaglini@arm.com            MaximumWidgets="12"
97213481Sgiacomo.travaglini@arm.com            MinimumWidgets="9" />
97313481Sgiacomo.travaglini@arm.com...
97413481Sgiacomo.travaglini@arm.com```
97513481Sgiacomo.travaglini@arm.com
97613481Sgiacomo.travaglini@arm.com_Note_:
97713481Sgiacomo.travaglini@arm.com  * `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.
97813481Sgiacomo.travaglini@arm.com  * `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`).
97913481Sgiacomo.travaglini@arm.com  * 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.
98013481Sgiacomo.travaglini@arm.com
98113481Sgiacomo.travaglini@arm.com_Availability_: Linux, Windows, Mac.
98213481Sgiacomo.travaglini@arm.com
98313481Sgiacomo.travaglini@arm.com# Sharing Resources Between Tests in the Same Test Case #
98413481Sgiacomo.travaglini@arm.com
98513481Sgiacomo.travaglini@arm.com
98613481Sgiacomo.travaglini@arm.com
98713481Sgiacomo.travaglini@arm.comGoogle Test creates a new test fixture object for each test in order to make
98813481Sgiacomo.travaglini@arm.comtests independent and easier to debug. However, sometimes tests use resources
98913481Sgiacomo.travaglini@arm.comthat are expensive to set up, making the one-copy-per-test model prohibitively
99013481Sgiacomo.travaglini@arm.comexpensive.
99113481Sgiacomo.travaglini@arm.com
99213481Sgiacomo.travaglini@arm.comIf the tests don't change the resource, there's no harm in them sharing a
99313481Sgiacomo.travaglini@arm.comsingle resource copy. So, in addition to per-test set-up/tear-down, Google Test
99413481Sgiacomo.travaglini@arm.comalso supports per-test-case set-up/tear-down. To use it:
99513481Sgiacomo.travaglini@arm.com
99613481Sgiacomo.travaglini@arm.com  1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources.
99713481Sgiacomo.travaglini@arm.com  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.
99813481Sgiacomo.travaglini@arm.com
99913481Sgiacomo.travaglini@arm.comThat's it! Google Test automatically calls `SetUpTestCase()` before running the
100013481Sgiacomo.travaglini@arm.com_first test_ in the `FooTest` test case (i.e. before creating the first
100113481Sgiacomo.travaglini@arm.com`FooTest` object), and calls `TearDownTestCase()` after running the _last test_
100213481Sgiacomo.travaglini@arm.comin it (i.e. after deleting the last `FooTest` object). In between, the tests
100313481Sgiacomo.travaglini@arm.comcan use the shared resources.
100413481Sgiacomo.travaglini@arm.com
100513481Sgiacomo.travaglini@arm.comRemember that the test order is undefined, so your code can't depend on a test
100613481Sgiacomo.travaglini@arm.compreceding or following another. Also, the tests must either not modify the
100713481Sgiacomo.travaglini@arm.comstate of any shared resource, or, if they do modify the state, they must
100813481Sgiacomo.travaglini@arm.comrestore the state to its original value before passing control to the next
100913481Sgiacomo.travaglini@arm.comtest.
101013481Sgiacomo.travaglini@arm.com
101113481Sgiacomo.travaglini@arm.comHere's an example of per-test-case set-up and tear-down:
101213481Sgiacomo.travaglini@arm.com```
101313481Sgiacomo.travaglini@arm.comclass FooTest : public ::testing::Test {
101413481Sgiacomo.travaglini@arm.com protected:
101513481Sgiacomo.travaglini@arm.com  // Per-test-case set-up.
101613481Sgiacomo.travaglini@arm.com  // Called before the first test in this test case.
101713481Sgiacomo.travaglini@arm.com  // Can be omitted if not needed.
101813481Sgiacomo.travaglini@arm.com  static void SetUpTestCase() {
101913481Sgiacomo.travaglini@arm.com    shared_resource_ = new ...;
102013481Sgiacomo.travaglini@arm.com  }
102113481Sgiacomo.travaglini@arm.com
102213481Sgiacomo.travaglini@arm.com  // Per-test-case tear-down.
102313481Sgiacomo.travaglini@arm.com  // Called after the last test in this test case.
102413481Sgiacomo.travaglini@arm.com  // Can be omitted if not needed.
102513481Sgiacomo.travaglini@arm.com  static void TearDownTestCase() {
102613481Sgiacomo.travaglini@arm.com    delete shared_resource_;
102713481Sgiacomo.travaglini@arm.com    shared_resource_ = NULL;
102813481Sgiacomo.travaglini@arm.com  }
102913481Sgiacomo.travaglini@arm.com
103013481Sgiacomo.travaglini@arm.com  // You can define per-test set-up and tear-down logic as usual.
103113481Sgiacomo.travaglini@arm.com  virtual void SetUp() { ... }
103213481Sgiacomo.travaglini@arm.com  virtual void TearDown() { ... }
103313481Sgiacomo.travaglini@arm.com
103413481Sgiacomo.travaglini@arm.com  // Some expensive resource shared by all tests.
103513481Sgiacomo.travaglini@arm.com  static T* shared_resource_;
103613481Sgiacomo.travaglini@arm.com};
103713481Sgiacomo.travaglini@arm.com
103813481Sgiacomo.travaglini@arm.comT* FooTest::shared_resource_ = NULL;
103913481Sgiacomo.travaglini@arm.com
104013481Sgiacomo.travaglini@arm.comTEST_F(FooTest, Test1) {
104113481Sgiacomo.travaglini@arm.com  ... you can refer to shared_resource here ...
104213481Sgiacomo.travaglini@arm.com}
104313481Sgiacomo.travaglini@arm.comTEST_F(FooTest, Test2) {
104413481Sgiacomo.travaglini@arm.com  ... you can refer to shared_resource here ...
104513481Sgiacomo.travaglini@arm.com}
104613481Sgiacomo.travaglini@arm.com```
104713481Sgiacomo.travaglini@arm.com
104813481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.
104913481Sgiacomo.travaglini@arm.com
105013481Sgiacomo.travaglini@arm.com# Global Set-Up and Tear-Down #
105113481Sgiacomo.travaglini@arm.com
105213481Sgiacomo.travaglini@arm.comJust as you can do set-up and tear-down at the test level and the test case
105313481Sgiacomo.travaglini@arm.comlevel, you can also do it at the test program level. Here's how.
105413481Sgiacomo.travaglini@arm.com
105513481Sgiacomo.travaglini@arm.comFirst, you subclass the `::testing::Environment` class to define a test
105613481Sgiacomo.travaglini@arm.comenvironment, which knows how to set-up and tear-down:
105713481Sgiacomo.travaglini@arm.com
105813481Sgiacomo.travaglini@arm.com```
105913481Sgiacomo.travaglini@arm.comclass Environment {
106013481Sgiacomo.travaglini@arm.com public:
106113481Sgiacomo.travaglini@arm.com  virtual ~Environment() {}
106213481Sgiacomo.travaglini@arm.com  // Override this to define how to set up the environment.
106313481Sgiacomo.travaglini@arm.com  virtual void SetUp() {}
106413481Sgiacomo.travaglini@arm.com  // Override this to define how to tear down the environment.
106513481Sgiacomo.travaglini@arm.com  virtual void TearDown() {}
106613481Sgiacomo.travaglini@arm.com};
106713481Sgiacomo.travaglini@arm.com```
106813481Sgiacomo.travaglini@arm.com
106913481Sgiacomo.travaglini@arm.comThen, you register an instance of your environment class with Google Test by
107013481Sgiacomo.travaglini@arm.comcalling the `::testing::AddGlobalTestEnvironment()` function:
107113481Sgiacomo.travaglini@arm.com
107213481Sgiacomo.travaglini@arm.com```
107313481Sgiacomo.travaglini@arm.comEnvironment* AddGlobalTestEnvironment(Environment* env);
107413481Sgiacomo.travaglini@arm.com```
107513481Sgiacomo.travaglini@arm.com
107613481Sgiacomo.travaglini@arm.comNow, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of
107713481Sgiacomo.travaglini@arm.comthe environment object, then runs the tests if there was no fatal failures, and
107813481Sgiacomo.travaglini@arm.comfinally calls `TearDown()` of the environment object.
107913481Sgiacomo.travaglini@arm.com
108013481Sgiacomo.travaglini@arm.comIt's OK to register multiple environment objects. In this case, their `SetUp()`
108113481Sgiacomo.travaglini@arm.comwill be called in the order they are registered, and their `TearDown()` will be
108213481Sgiacomo.travaglini@arm.comcalled in the reverse order.
108313481Sgiacomo.travaglini@arm.com
108413481Sgiacomo.travaglini@arm.comNote that Google Test takes ownership of the registered environment objects.
108513481Sgiacomo.travaglini@arm.comTherefore **do not delete them** by yourself.
108613481Sgiacomo.travaglini@arm.com
108713481Sgiacomo.travaglini@arm.comYou should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is
108813481Sgiacomo.travaglini@arm.comcalled, probably in `main()`. If you use `gtest_main`, you need to      call
108913481Sgiacomo.travaglini@arm.comthis before `main()` starts for it to take effect. One way to do this is to
109013481Sgiacomo.travaglini@arm.comdefine a global variable like this:
109113481Sgiacomo.travaglini@arm.com
109213481Sgiacomo.travaglini@arm.com```
109313481Sgiacomo.travaglini@arm.com::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment);
109413481Sgiacomo.travaglini@arm.com```
109513481Sgiacomo.travaglini@arm.com
109613481Sgiacomo.travaglini@arm.comHowever, we strongly recommend you to write your own `main()` and call
109713481Sgiacomo.travaglini@arm.com`AddGlobalTestEnvironment()` there, as relying on initialization of global
109813481Sgiacomo.travaglini@arm.comvariables makes the code harder to read and may cause problems when you
109913481Sgiacomo.travaglini@arm.comregister multiple environments from different translation units and the
110013481Sgiacomo.travaglini@arm.comenvironments have dependencies among them (remember that the compiler doesn't
110113481Sgiacomo.travaglini@arm.comguarantee the order in which global variables from different translation units
110213481Sgiacomo.travaglini@arm.comare initialized).
110313481Sgiacomo.travaglini@arm.com
110413481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.
110513481Sgiacomo.travaglini@arm.com
110613481Sgiacomo.travaglini@arm.com
110713481Sgiacomo.travaglini@arm.com# Value Parameterized Tests #
110813481Sgiacomo.travaglini@arm.com
110913481Sgiacomo.travaglini@arm.com_Value-parameterized tests_ allow you to test your code with different
111013481Sgiacomo.travaglini@arm.comparameters without writing multiple copies of the same test.
111113481Sgiacomo.travaglini@arm.com
111213481Sgiacomo.travaglini@arm.comSuppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag.
111313481Sgiacomo.travaglini@arm.com
111413481Sgiacomo.travaglini@arm.com```
111513481Sgiacomo.travaglini@arm.comTEST(MyCodeTest, TestFoo) {
111613481Sgiacomo.travaglini@arm.com  // A code to test foo().
111713481Sgiacomo.travaglini@arm.com}
111813481Sgiacomo.travaglini@arm.com```
111913481Sgiacomo.travaglini@arm.com
112013481Sgiacomo.travaglini@arm.comUsually 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.
112113481Sgiacomo.travaglini@arm.com
112213481Sgiacomo.travaglini@arm.com```
112313481Sgiacomo.travaglini@arm.comvoid TestFooHelper(bool flag_value) {
112413481Sgiacomo.travaglini@arm.com  flag = flag_value;
112513481Sgiacomo.travaglini@arm.com  // A code to test foo().
112613481Sgiacomo.travaglini@arm.com}
112713481Sgiacomo.travaglini@arm.com
112813481Sgiacomo.travaglini@arm.comTEST(MyCodeTest, TestFoo) {
112913481Sgiacomo.travaglini@arm.com  TestFooHelper(false);
113013481Sgiacomo.travaglini@arm.com  TestFooHelper(true);
113113481Sgiacomo.travaglini@arm.com}
113213481Sgiacomo.travaglini@arm.com```
113313481Sgiacomo.travaglini@arm.com
113413481Sgiacomo.travaglini@arm.comBut 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?
113513481Sgiacomo.travaglini@arm.com
113613481Sgiacomo.travaglini@arm.comValue-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values.
113713481Sgiacomo.travaglini@arm.com
113813481Sgiacomo.travaglini@arm.comHere are some other situations when value-parameterized tests come handy:
113913481Sgiacomo.travaglini@arm.com
114013481Sgiacomo.travaglini@arm.com  * You want to test different implementations of an OO interface.
114113481Sgiacomo.travaglini@arm.com  * 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!
114213481Sgiacomo.travaglini@arm.com
114313481Sgiacomo.travaglini@arm.com## How to Write Value-Parameterized Tests ##
114413481Sgiacomo.travaglini@arm.com
114513481Sgiacomo.travaglini@arm.comTo write value-parameterized tests, first you should define a fixture
114613481Sgiacomo.travaglini@arm.comclass.  It must be derived from both `::testing::Test` and
114713481Sgiacomo.travaglini@arm.com`::testing::WithParamInterface<T>` (the latter is a pure interface),
114813481Sgiacomo.travaglini@arm.comwhere `T` is the type of your parameter values.  For convenience, you
114913481Sgiacomo.travaglini@arm.comcan just derive the fixture class from `::testing::TestWithParam<T>`,
115013481Sgiacomo.travaglini@arm.comwhich itself is derived from both `::testing::Test` and
115113481Sgiacomo.travaglini@arm.com`::testing::WithParamInterface<T>`. `T` can be any copyable type. If
115213481Sgiacomo.travaglini@arm.comit's a raw pointer, you are responsible for managing the lifespan of
115313481Sgiacomo.travaglini@arm.comthe pointed values.
115413481Sgiacomo.travaglini@arm.com
115513481Sgiacomo.travaglini@arm.com```
115613481Sgiacomo.travaglini@arm.comclass FooTest : public ::testing::TestWithParam<const char*> {
115713481Sgiacomo.travaglini@arm.com  // You can implement all the usual fixture class members here.
115813481Sgiacomo.travaglini@arm.com  // To access the test parameter, call GetParam() from class
115913481Sgiacomo.travaglini@arm.com  // TestWithParam<T>.
116013481Sgiacomo.travaglini@arm.com};
116113481Sgiacomo.travaglini@arm.com
116213481Sgiacomo.travaglini@arm.com// Or, when you want to add parameters to a pre-existing fixture class:
116313481Sgiacomo.travaglini@arm.comclass BaseTest : public ::testing::Test {
116413481Sgiacomo.travaglini@arm.com  ...
116513481Sgiacomo.travaglini@arm.com};
116613481Sgiacomo.travaglini@arm.comclass BarTest : public BaseTest,
116713481Sgiacomo.travaglini@arm.com                public ::testing::WithParamInterface<const char*> {
116813481Sgiacomo.travaglini@arm.com  ...
116913481Sgiacomo.travaglini@arm.com};
117013481Sgiacomo.travaglini@arm.com```
117113481Sgiacomo.travaglini@arm.com
117213481Sgiacomo.travaglini@arm.comThen, use the `TEST_P` macro to define as many test patterns using
117313481Sgiacomo.travaglini@arm.comthis fixture as you want.  The `_P` suffix is for "parameterized" or
117413481Sgiacomo.travaglini@arm.com"pattern", whichever you prefer to think.
117513481Sgiacomo.travaglini@arm.com
117613481Sgiacomo.travaglini@arm.com```
117713481Sgiacomo.travaglini@arm.comTEST_P(FooTest, DoesBlah) {
117813481Sgiacomo.travaglini@arm.com  // Inside a test, access the test parameter with the GetParam() method
117913481Sgiacomo.travaglini@arm.com  // of the TestWithParam<T> class:
118013481Sgiacomo.travaglini@arm.com  EXPECT_TRUE(foo.Blah(GetParam()));
118113481Sgiacomo.travaglini@arm.com  ...
118213481Sgiacomo.travaglini@arm.com}
118313481Sgiacomo.travaglini@arm.com
118413481Sgiacomo.travaglini@arm.comTEST_P(FooTest, HasBlahBlah) {
118513481Sgiacomo.travaglini@arm.com  ...
118613481Sgiacomo.travaglini@arm.com}
118713481Sgiacomo.travaglini@arm.com```
118813481Sgiacomo.travaglini@arm.com
118913481Sgiacomo.travaglini@arm.comFinally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test
119013481Sgiacomo.travaglini@arm.comcase with any set of parameters you want. Google Test defines a number of
119113481Sgiacomo.travaglini@arm.comfunctions for generating test parameters. They return what we call
119213481Sgiacomo.travaglini@arm.com(surprise!) _parameter generators_. Here is a summary of them,
119313481Sgiacomo.travaglini@arm.comwhich are all in the `testing` namespace:
119413481Sgiacomo.travaglini@arm.com
119513481Sgiacomo.travaglini@arm.com| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. |
119613481Sgiacomo.travaglini@arm.com|:----------------------------|:------------------------------------------------------------------------------------------------------------------|
119713481Sgiacomo.travaglini@arm.com| `Values(v1, v2, ..., vN)`   | Yields values `{v1, v2, ..., vN}`.                                                                                |
119813481Sgiacomo.travaglini@arm.com| `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.  |
119913481Sgiacomo.travaglini@arm.com| `Bool()`                    | Yields sequence `{false, true}`.                                                                                  |
120013481Sgiacomo.travaglini@arm.com| `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. |
120113481Sgiacomo.travaglini@arm.com
120213481Sgiacomo.travaglini@arm.comFor more details, see the comments at the definitions of these functions in the [source code](../include/gtest/gtest-param-test.h).
120313481Sgiacomo.travaglini@arm.com
120413481Sgiacomo.travaglini@arm.comThe following statement will instantiate tests from the `FooTest` test case
120513481Sgiacomo.travaglini@arm.comeach with parameter values `"meeny"`, `"miny"`, and `"moe"`.
120613481Sgiacomo.travaglini@arm.com
120713481Sgiacomo.travaglini@arm.com```
120813481Sgiacomo.travaglini@arm.comINSTANTIATE_TEST_CASE_P(InstantiationName,
120913481Sgiacomo.travaglini@arm.com                        FooTest,
121013481Sgiacomo.travaglini@arm.com                        ::testing::Values("meeny", "miny", "moe"));
121113481Sgiacomo.travaglini@arm.com```
121213481Sgiacomo.travaglini@arm.com
121313481Sgiacomo.travaglini@arm.comTo distinguish different instances of the pattern (yes, you can
121413481Sgiacomo.travaglini@arm.cominstantiate it more than once), the first argument to
121513481Sgiacomo.travaglini@arm.com`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual
121613481Sgiacomo.travaglini@arm.comtest case name. Remember to pick unique prefixes for different
121713481Sgiacomo.travaglini@arm.cominstantiations. The tests from the instantiation above will have these
121813481Sgiacomo.travaglini@arm.comnames:
121913481Sgiacomo.travaglini@arm.com
122013481Sgiacomo.travaglini@arm.com  * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"`
122113481Sgiacomo.travaglini@arm.com  * `InstantiationName/FooTest.DoesBlah/1` for `"miny"`
122213481Sgiacomo.travaglini@arm.com  * `InstantiationName/FooTest.DoesBlah/2` for `"moe"`
122313481Sgiacomo.travaglini@arm.com  * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"`
122413481Sgiacomo.travaglini@arm.com  * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"`
122513481Sgiacomo.travaglini@arm.com  * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"`
122613481Sgiacomo.travaglini@arm.com
122713481Sgiacomo.travaglini@arm.comYou can use these names in [--gtest\_filter](#running-a-subset-of-the-tests).
122813481Sgiacomo.travaglini@arm.com
122913481Sgiacomo.travaglini@arm.comThis statement will instantiate all tests from `FooTest` again, each
123013481Sgiacomo.travaglini@arm.comwith parameter values `"cat"` and `"dog"`:
123113481Sgiacomo.travaglini@arm.com
123213481Sgiacomo.travaglini@arm.com```
123313481Sgiacomo.travaglini@arm.comconst char* pets[] = {"cat", "dog"};
123413481Sgiacomo.travaglini@arm.comINSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest,
123513481Sgiacomo.travaglini@arm.com                        ::testing::ValuesIn(pets));
123613481Sgiacomo.travaglini@arm.com```
123713481Sgiacomo.travaglini@arm.com
123813481Sgiacomo.travaglini@arm.comThe tests from the instantiation above will have these names:
123913481Sgiacomo.travaglini@arm.com
124013481Sgiacomo.travaglini@arm.com  * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"`
124113481Sgiacomo.travaglini@arm.com  * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"`
124213481Sgiacomo.travaglini@arm.com  * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"`
124313481Sgiacomo.travaglini@arm.com  * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"`
124413481Sgiacomo.travaglini@arm.com
124513481Sgiacomo.travaglini@arm.comPlease note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_
124613481Sgiacomo.travaglini@arm.comtests in the given test case, whether their definitions come before or
124713481Sgiacomo.travaglini@arm.com_after_ the `INSTANTIATE_TEST_CASE_P` statement.
124813481Sgiacomo.travaglini@arm.com
124913481Sgiacomo.travaglini@arm.comYou can see
125013481Sgiacomo.travaglini@arm.com[these](../samples/sample7_unittest.cc)
125113481Sgiacomo.travaglini@arm.com[files](../samples/sample8_unittest.cc) for more examples.
125213481Sgiacomo.travaglini@arm.com
125313481Sgiacomo.travaglini@arm.com_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0.
125413481Sgiacomo.travaglini@arm.com
125513481Sgiacomo.travaglini@arm.com## Creating Value-Parameterized Abstract Tests ##
125613481Sgiacomo.travaglini@arm.com
125713481Sgiacomo.travaglini@arm.comIn the above, we define and instantiate `FooTest` in the same source
125813481Sgiacomo.travaglini@arm.comfile. Sometimes you may want to define value-parameterized tests in a
125913481Sgiacomo.travaglini@arm.comlibrary and let other people instantiate them later. This pattern is
126013481Sgiacomo.travaglini@arm.comknown as <i>abstract tests</i>. As an example of its application, when you
126113481Sgiacomo.travaglini@arm.comare designing an interface you can write a standard suite of abstract
126213481Sgiacomo.travaglini@arm.comtests (perhaps using a factory function as the test parameter) that
126313481Sgiacomo.travaglini@arm.comall implementations of the interface are expected to pass. When
126413481Sgiacomo.travaglini@arm.comsomeone implements the interface, he can instantiate your suite to get
126513481Sgiacomo.travaglini@arm.comall the interface-conformance tests for free.
126613481Sgiacomo.travaglini@arm.com
126713481Sgiacomo.travaglini@arm.comTo define abstract tests, you should organize your code like this:
126813481Sgiacomo.travaglini@arm.com
126913481Sgiacomo.travaglini@arm.com  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.
127013481Sgiacomo.travaglini@arm.com  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.
127113481Sgiacomo.travaglini@arm.com
127213481Sgiacomo.travaglini@arm.comOnce they are defined, you can instantiate them by including
127313481Sgiacomo.travaglini@arm.com`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking
127413481Sgiacomo.travaglini@arm.comwith `foo_param_test.cc`. You can instantiate the same abstract test
127513481Sgiacomo.travaglini@arm.comcase multiple times, possibly in different source files.
127613481Sgiacomo.travaglini@arm.com
127713481Sgiacomo.travaglini@arm.com# Typed Tests #
127813481Sgiacomo.travaglini@arm.com
127913481Sgiacomo.travaglini@arm.comSuppose you have multiple implementations of the same interface and
128013481Sgiacomo.travaglini@arm.comwant to make sure that all of them satisfy some common requirements.
128113481Sgiacomo.travaglini@arm.comOr, you may have defined several types that are supposed to conform to
128213481Sgiacomo.travaglini@arm.comthe same "concept" and you want to verify it.  In both cases, you want
128313481Sgiacomo.travaglini@arm.comthe same test logic repeated for different types.
128413481Sgiacomo.travaglini@arm.com
128513481Sgiacomo.travaglini@arm.comWhile you can write one `TEST` or `TEST_F` for each type you want to
128613481Sgiacomo.travaglini@arm.comtest (and you may even factor the test logic into a function template
128713481Sgiacomo.travaglini@arm.comthat you invoke from the `TEST`), it's tedious and doesn't scale:
128813481Sgiacomo.travaglini@arm.comif you want _m_ tests over _n_ types, you'll end up writing _m\*n_
128913481Sgiacomo.travaglini@arm.com`TEST`s.
129013481Sgiacomo.travaglini@arm.com
129113481Sgiacomo.travaglini@arm.com_Typed tests_ allow you to repeat the same test logic over a list of
129213481Sgiacomo.travaglini@arm.comtypes.  You only need to write the test logic once, although you must
129313481Sgiacomo.travaglini@arm.comknow the type list when writing typed tests.  Here's how you do it:
129413481Sgiacomo.travaglini@arm.com
129513481Sgiacomo.travaglini@arm.comFirst, define a fixture class template.  It should be parameterized
129613481Sgiacomo.travaglini@arm.comby a type.  Remember to derive it from `::testing::Test`:
129713481Sgiacomo.travaglini@arm.com
129813481Sgiacomo.travaglini@arm.com```
129913481Sgiacomo.travaglini@arm.comtemplate <typename T>
130013481Sgiacomo.travaglini@arm.comclass FooTest : public ::testing::Test {
130113481Sgiacomo.travaglini@arm.com public:
130213481Sgiacomo.travaglini@arm.com  ...
130313481Sgiacomo.travaglini@arm.com  typedef std::list<T> List;
130413481Sgiacomo.travaglini@arm.com  static T shared_;
130513481Sgiacomo.travaglini@arm.com  T value_;
130613481Sgiacomo.travaglini@arm.com};
130713481Sgiacomo.travaglini@arm.com```
130813481Sgiacomo.travaglini@arm.com
130913481Sgiacomo.travaglini@arm.comNext, associate a list of types with the test case, which will be
131013481Sgiacomo.travaglini@arm.comrepeated for each type in the list:
131113481Sgiacomo.travaglini@arm.com
131213481Sgiacomo.travaglini@arm.com```
131313481Sgiacomo.travaglini@arm.comtypedef ::testing::Types<char, int, unsigned int> MyTypes;
131413481Sgiacomo.travaglini@arm.comTYPED_TEST_CASE(FooTest, MyTypes);
131513481Sgiacomo.travaglini@arm.com```
131613481Sgiacomo.travaglini@arm.com
131713481Sgiacomo.travaglini@arm.comThe `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse
131813481Sgiacomo.travaglini@arm.comcorrectly.  Otherwise the compiler will think that each comma in the
131913481Sgiacomo.travaglini@arm.comtype list introduces a new macro argument.
132013481Sgiacomo.travaglini@arm.com
132113481Sgiacomo.travaglini@arm.comThen, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test
132213481Sgiacomo.travaglini@arm.comfor this test case.  You can repeat this as many times as you want:
132313481Sgiacomo.travaglini@arm.com
132413481Sgiacomo.travaglini@arm.com```
132513481Sgiacomo.travaglini@arm.comTYPED_TEST(FooTest, DoesBlah) {
132613481Sgiacomo.travaglini@arm.com  // Inside a test, refer to the special name TypeParam to get the type
132713481Sgiacomo.travaglini@arm.com  // parameter.  Since we are inside a derived class template, C++ requires
132813481Sgiacomo.travaglini@arm.com  // us to visit the members of FooTest via 'this'.
132913481Sgiacomo.travaglini@arm.com  TypeParam n = this->value_;
133013481Sgiacomo.travaglini@arm.com
133113481Sgiacomo.travaglini@arm.com  // To visit static members of the fixture, add the 'TestFixture::'
133213481Sgiacomo.travaglini@arm.com  // prefix.
133313481Sgiacomo.travaglini@arm.com  n += TestFixture::shared_;
133413481Sgiacomo.travaglini@arm.com
133513481Sgiacomo.travaglini@arm.com  // To refer to typedefs in the fixture, add the 'typename TestFixture::'
133613481Sgiacomo.travaglini@arm.com  // prefix.  The 'typename' is required to satisfy the compiler.
133713481Sgiacomo.travaglini@arm.com  typename TestFixture::List values;
133813481Sgiacomo.travaglini@arm.com  values.push_back(n);
133913481Sgiacomo.travaglini@arm.com  ...
134013481Sgiacomo.travaglini@arm.com}
134113481Sgiacomo.travaglini@arm.com
134213481Sgiacomo.travaglini@arm.comTYPED_TEST(FooTest, HasPropertyA) { ... }
134313481Sgiacomo.travaglini@arm.com```
134413481Sgiacomo.travaglini@arm.com
134513481Sgiacomo.travaglini@arm.comYou can see `samples/sample6_unittest.cc` for a complete example.
134613481Sgiacomo.travaglini@arm.com
134713481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
134813481Sgiacomo.travaglini@arm.comsince version 1.1.0.
134913481Sgiacomo.travaglini@arm.com
135013481Sgiacomo.travaglini@arm.com# Type-Parameterized Tests #
135113481Sgiacomo.travaglini@arm.com
135213481Sgiacomo.travaglini@arm.com_Type-parameterized tests_ are like typed tests, except that they
135313481Sgiacomo.travaglini@arm.comdon't require you to know the list of types ahead of time.  Instead,
135413481Sgiacomo.travaglini@arm.comyou can define the test logic first and instantiate it with different
135513481Sgiacomo.travaglini@arm.comtype lists later.  You can even instantiate it more than once in the
135613481Sgiacomo.travaglini@arm.comsame program.
135713481Sgiacomo.travaglini@arm.com
135813481Sgiacomo.travaglini@arm.comIf you are designing an interface or concept, you can define a suite
135913481Sgiacomo.travaglini@arm.comof type-parameterized tests to verify properties that any valid
136013481Sgiacomo.travaglini@arm.comimplementation of the interface/concept should have.  Then, the author
136113481Sgiacomo.travaglini@arm.comof each implementation can just instantiate the test suite with his
136213481Sgiacomo.travaglini@arm.comtype to verify that it conforms to the requirements, without having to
136313481Sgiacomo.travaglini@arm.comwrite similar tests repeatedly.  Here's an example:
136413481Sgiacomo.travaglini@arm.com
136513481Sgiacomo.travaglini@arm.comFirst, define a fixture class template, as we did with typed tests:
136613481Sgiacomo.travaglini@arm.com
136713481Sgiacomo.travaglini@arm.com```
136813481Sgiacomo.travaglini@arm.comtemplate <typename T>
136913481Sgiacomo.travaglini@arm.comclass FooTest : public ::testing::Test {
137013481Sgiacomo.travaglini@arm.com  ...
137113481Sgiacomo.travaglini@arm.com};
137213481Sgiacomo.travaglini@arm.com```
137313481Sgiacomo.travaglini@arm.com
137413481Sgiacomo.travaglini@arm.comNext, declare that you will define a type-parameterized test case:
137513481Sgiacomo.travaglini@arm.com
137613481Sgiacomo.travaglini@arm.com```
137713481Sgiacomo.travaglini@arm.comTYPED_TEST_CASE_P(FooTest);
137813481Sgiacomo.travaglini@arm.com```
137913481Sgiacomo.travaglini@arm.com
138013481Sgiacomo.travaglini@arm.comThe `_P` suffix is for "parameterized" or "pattern", whichever you
138113481Sgiacomo.travaglini@arm.comprefer to think.
138213481Sgiacomo.travaglini@arm.com
138313481Sgiacomo.travaglini@arm.comThen, use `TYPED_TEST_P()` to define a type-parameterized test.  You
138413481Sgiacomo.travaglini@arm.comcan repeat this as many times as you want:
138513481Sgiacomo.travaglini@arm.com
138613481Sgiacomo.travaglini@arm.com```
138713481Sgiacomo.travaglini@arm.comTYPED_TEST_P(FooTest, DoesBlah) {
138813481Sgiacomo.travaglini@arm.com  // Inside a test, refer to TypeParam to get the type parameter.
138913481Sgiacomo.travaglini@arm.com  TypeParam n = 0;
139013481Sgiacomo.travaglini@arm.com  ...
139113481Sgiacomo.travaglini@arm.com}
139213481Sgiacomo.travaglini@arm.com
139313481Sgiacomo.travaglini@arm.comTYPED_TEST_P(FooTest, HasPropertyA) { ... }
139413481Sgiacomo.travaglini@arm.com```
139513481Sgiacomo.travaglini@arm.com
139613481Sgiacomo.travaglini@arm.comNow the tricky part: you need to register all test patterns using the
139713481Sgiacomo.travaglini@arm.com`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them.
139813481Sgiacomo.travaglini@arm.comThe first argument of the macro is the test case name; the rest are
139913481Sgiacomo.travaglini@arm.comthe names of the tests in this test case:
140013481Sgiacomo.travaglini@arm.com
140113481Sgiacomo.travaglini@arm.com```
140213481Sgiacomo.travaglini@arm.comREGISTER_TYPED_TEST_CASE_P(FooTest,
140313481Sgiacomo.travaglini@arm.com                           DoesBlah, HasPropertyA);
140413481Sgiacomo.travaglini@arm.com```
140513481Sgiacomo.travaglini@arm.com
140613481Sgiacomo.travaglini@arm.comFinally, you are free to instantiate the pattern with the types you
140713481Sgiacomo.travaglini@arm.comwant.  If you put the above code in a header file, you can `#include`
140813481Sgiacomo.travaglini@arm.comit in multiple C++ source files and instantiate it multiple times.
140913481Sgiacomo.travaglini@arm.com
141013481Sgiacomo.travaglini@arm.com```
141113481Sgiacomo.travaglini@arm.comtypedef ::testing::Types<char, int, unsigned int> MyTypes;
141213481Sgiacomo.travaglini@arm.comINSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
141313481Sgiacomo.travaglini@arm.com```
141413481Sgiacomo.travaglini@arm.com
141513481Sgiacomo.travaglini@arm.comTo distinguish different instances of the pattern, the first argument
141613481Sgiacomo.travaglini@arm.comto the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be
141713481Sgiacomo.travaglini@arm.comadded to the actual test case name.  Remember to pick unique prefixes
141813481Sgiacomo.travaglini@arm.comfor different instances.
141913481Sgiacomo.travaglini@arm.com
142013481Sgiacomo.travaglini@arm.comIn the special case where the type list contains only one type, you
142113481Sgiacomo.travaglini@arm.comcan write that type directly without `::testing::Types<...>`, like this:
142213481Sgiacomo.travaglini@arm.com
142313481Sgiacomo.travaglini@arm.com```
142413481Sgiacomo.travaglini@arm.comINSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int);
142513481Sgiacomo.travaglini@arm.com```
142613481Sgiacomo.travaglini@arm.com
142713481Sgiacomo.travaglini@arm.comYou can see `samples/sample6_unittest.cc` for a complete example.
142813481Sgiacomo.travaglini@arm.com
142913481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
143013481Sgiacomo.travaglini@arm.comsince version 1.1.0.
143113481Sgiacomo.travaglini@arm.com
143213481Sgiacomo.travaglini@arm.com# Testing Private Code #
143313481Sgiacomo.travaglini@arm.com
143413481Sgiacomo.travaglini@arm.comIf you change your software's internal implementation, your tests should not
143513481Sgiacomo.travaglini@arm.combreak as long as the change is not observable by users. Therefore, per the
143613481Sgiacomo.travaglini@arm.com_black-box testing principle_, most of the time you should test your code
143713481Sgiacomo.travaglini@arm.comthrough its public interfaces.
143813481Sgiacomo.travaglini@arm.com
143913481Sgiacomo.travaglini@arm.comIf you still find yourself needing to test internal implementation code,
144013481Sgiacomo.travaglini@arm.comconsider if there's a better design that wouldn't require you to do so. If you
144113481Sgiacomo.travaglini@arm.comabsolutely have to test non-public interface code though, you can. There are
144213481Sgiacomo.travaglini@arm.comtwo cases to consider:
144313481Sgiacomo.travaglini@arm.com
144413481Sgiacomo.travaglini@arm.com  * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and
144513481Sgiacomo.travaglini@arm.com  * Private or protected class members
144613481Sgiacomo.travaglini@arm.com
144713481Sgiacomo.travaglini@arm.com## Static Functions ##
144813481Sgiacomo.travaglini@arm.com
144913481Sgiacomo.travaglini@arm.comBoth static functions and definitions/declarations in an unnamed namespace are
145013481Sgiacomo.travaglini@arm.comonly visible within the same translation unit. To test them, you can `#include`
145113481Sgiacomo.travaglini@arm.comthe entire `.cc` file being tested in your `*_test.cc` file. (`#include`ing `.cc`
145213481Sgiacomo.travaglini@arm.comfiles is not a good way to reuse code - you should not do this in production
145313481Sgiacomo.travaglini@arm.comcode!)
145413481Sgiacomo.travaglini@arm.com
145513481Sgiacomo.travaglini@arm.comHowever, a better approach is to move the private code into the
145613481Sgiacomo.travaglini@arm.com`foo::internal` namespace, where `foo` is the namespace your project normally
145713481Sgiacomo.travaglini@arm.comuses, and put the private declarations in a `*-internal.h` file. Your
145813481Sgiacomo.travaglini@arm.comproduction `.cc` files and your tests are allowed to include this internal
145913481Sgiacomo.travaglini@arm.comheader, but your clients are not. This way, you can fully test your internal
146013481Sgiacomo.travaglini@arm.comimplementation without leaking it to your clients.
146113481Sgiacomo.travaglini@arm.com
146213481Sgiacomo.travaglini@arm.com## Private Class Members ##
146313481Sgiacomo.travaglini@arm.com
146413481Sgiacomo.travaglini@arm.comPrivate class members are only accessible from within the class or by friends.
146513481Sgiacomo.travaglini@arm.comTo access a class' private members, you can declare your test fixture as a
146613481Sgiacomo.travaglini@arm.comfriend to the class and define accessors in your fixture. Tests using the
146713481Sgiacomo.travaglini@arm.comfixture can then access the private members of your production class via the
146813481Sgiacomo.travaglini@arm.comaccessors in the fixture. Note that even though your fixture is a friend to
146913481Sgiacomo.travaglini@arm.comyour production class, your tests are not automatically friends to it, as they
147013481Sgiacomo.travaglini@arm.comare technically defined in sub-classes of the fixture.
147113481Sgiacomo.travaglini@arm.com
147213481Sgiacomo.travaglini@arm.comAnother way to test private members is to refactor them into an implementation
147313481Sgiacomo.travaglini@arm.comclass, which is then declared in a `*-internal.h` file. Your clients aren't
147413481Sgiacomo.travaglini@arm.comallowed to include this header but your tests can. Such is called the Pimpl
147513481Sgiacomo.travaglini@arm.com(Private Implementation) idiom.
147613481Sgiacomo.travaglini@arm.com
147713481Sgiacomo.travaglini@arm.comOr, you can declare an individual test as a friend of your class by adding this
147813481Sgiacomo.travaglini@arm.comline in the class body:
147913481Sgiacomo.travaglini@arm.com
148013481Sgiacomo.travaglini@arm.com```
148113481Sgiacomo.travaglini@arm.comFRIEND_TEST(TestCaseName, TestName);
148213481Sgiacomo.travaglini@arm.com```
148313481Sgiacomo.travaglini@arm.com
148413481Sgiacomo.travaglini@arm.comFor example,
148513481Sgiacomo.travaglini@arm.com```
148613481Sgiacomo.travaglini@arm.com// foo.h
148713481Sgiacomo.travaglini@arm.com#include "gtest/gtest_prod.h"
148813481Sgiacomo.travaglini@arm.com
148913481Sgiacomo.travaglini@arm.com// Defines FRIEND_TEST.
149013481Sgiacomo.travaglini@arm.comclass Foo {
149113481Sgiacomo.travaglini@arm.com  ...
149213481Sgiacomo.travaglini@arm.com private:
149313481Sgiacomo.travaglini@arm.com  FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
149413481Sgiacomo.travaglini@arm.com  int Bar(void* x);
149513481Sgiacomo.travaglini@arm.com};
149613481Sgiacomo.travaglini@arm.com
149713481Sgiacomo.travaglini@arm.com// foo_test.cc
149813481Sgiacomo.travaglini@arm.com...
149913481Sgiacomo.travaglini@arm.comTEST(FooTest, BarReturnsZeroOnNull) {
150013481Sgiacomo.travaglini@arm.com  Foo foo;
150113481Sgiacomo.travaglini@arm.com  EXPECT_EQ(0, foo.Bar(NULL));
150213481Sgiacomo.travaglini@arm.com  // Uses Foo's private member Bar().
150313481Sgiacomo.travaglini@arm.com}
150413481Sgiacomo.travaglini@arm.com```
150513481Sgiacomo.travaglini@arm.com
150613481Sgiacomo.travaglini@arm.comPay special attention when your class is defined in a namespace, as you should
150713481Sgiacomo.travaglini@arm.comdefine your test fixtures and tests in the same namespace if you want them to
150813481Sgiacomo.travaglini@arm.combe friends of your class. For example, if the code to be tested looks like:
150913481Sgiacomo.travaglini@arm.com
151013481Sgiacomo.travaglini@arm.com```
151113481Sgiacomo.travaglini@arm.comnamespace my_namespace {
151213481Sgiacomo.travaglini@arm.com
151313481Sgiacomo.travaglini@arm.comclass Foo {
151413481Sgiacomo.travaglini@arm.com  friend class FooTest;
151513481Sgiacomo.travaglini@arm.com  FRIEND_TEST(FooTest, Bar);
151613481Sgiacomo.travaglini@arm.com  FRIEND_TEST(FooTest, Baz);
151713481Sgiacomo.travaglini@arm.com  ...
151813481Sgiacomo.travaglini@arm.com  definition of the class Foo
151913481Sgiacomo.travaglini@arm.com  ...
152013481Sgiacomo.travaglini@arm.com};
152113481Sgiacomo.travaglini@arm.com
152213481Sgiacomo.travaglini@arm.com}  // namespace my_namespace
152313481Sgiacomo.travaglini@arm.com```
152413481Sgiacomo.travaglini@arm.com
152513481Sgiacomo.travaglini@arm.comYour test code should be something like:
152613481Sgiacomo.travaglini@arm.com
152713481Sgiacomo.travaglini@arm.com```
152813481Sgiacomo.travaglini@arm.comnamespace my_namespace {
152913481Sgiacomo.travaglini@arm.comclass FooTest : public ::testing::Test {
153013481Sgiacomo.travaglini@arm.com protected:
153113481Sgiacomo.travaglini@arm.com  ...
153213481Sgiacomo.travaglini@arm.com};
153313481Sgiacomo.travaglini@arm.com
153413481Sgiacomo.travaglini@arm.comTEST_F(FooTest, Bar) { ... }
153513481Sgiacomo.travaglini@arm.comTEST_F(FooTest, Baz) { ... }
153613481Sgiacomo.travaglini@arm.com
153713481Sgiacomo.travaglini@arm.com}  // namespace my_namespace
153813481Sgiacomo.travaglini@arm.com```
153913481Sgiacomo.travaglini@arm.com
154013481Sgiacomo.travaglini@arm.com# Catching Failures #
154113481Sgiacomo.travaglini@arm.com
154213481Sgiacomo.travaglini@arm.comIf you are building a testing utility on top of Google Test, you'll
154313481Sgiacomo.travaglini@arm.comwant to test your utility.  What framework would you use to test it?
154413481Sgiacomo.travaglini@arm.comGoogle Test, of course.
154513481Sgiacomo.travaglini@arm.com
154613481Sgiacomo.travaglini@arm.comThe challenge is to verify that your testing utility reports failures
154713481Sgiacomo.travaglini@arm.comcorrectly.  In frameworks that report a failure by throwing an
154813481Sgiacomo.travaglini@arm.comexception, you could catch the exception and assert on it.  But Google
154913481Sgiacomo.travaglini@arm.comTest doesn't use exceptions, so how do we test that a piece of code
155013481Sgiacomo.travaglini@arm.comgenerates an expected failure?
155113481Sgiacomo.travaglini@arm.com
155213481Sgiacomo.travaglini@arm.com`"gtest/gtest-spi.h"` contains some constructs to do this.  After
155313481Sgiacomo.travaglini@arm.com`#include`ing this header, you can use
155413481Sgiacomo.travaglini@arm.com
155513481Sgiacomo.travaglini@arm.com| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` |
155613481Sgiacomo.travaglini@arm.com|:--------------------------------------------------|
155713481Sgiacomo.travaglini@arm.com
155813481Sgiacomo.travaglini@arm.comto assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure
155913481Sgiacomo.travaglini@arm.comwhose message contains the given _substring_, or use
156013481Sgiacomo.travaglini@arm.com
156113481Sgiacomo.travaglini@arm.com| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` |
156213481Sgiacomo.travaglini@arm.com|:-----------------------------------------------------|
156313481Sgiacomo.travaglini@arm.com
156413481Sgiacomo.travaglini@arm.comif you are expecting a non-fatal (e.g. `EXPECT_*`) failure.
156513481Sgiacomo.travaglini@arm.com
156613481Sgiacomo.travaglini@arm.comFor technical reasons, there are some caveats:
156713481Sgiacomo.travaglini@arm.com
156813481Sgiacomo.travaglini@arm.com  1. You cannot stream a failure message to either macro.
156913481Sgiacomo.travaglini@arm.com  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object.
157013481Sgiacomo.travaglini@arm.com  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value.
157113481Sgiacomo.travaglini@arm.com
157213481Sgiacomo.travaglini@arm.com_Note:_ Google Test is designed with threads in mind.  Once the
157313481Sgiacomo.travaglini@arm.comsynchronization primitives in `"gtest/internal/gtest-port.h"` have
157413481Sgiacomo.travaglini@arm.combeen implemented, Google Test will become thread-safe, meaning that
157513481Sgiacomo.travaglini@arm.comyou can then use assertions in multiple threads concurrently.  Before
157613481Sgiacomo.travaglini@arm.com
157713481Sgiacomo.travaglini@arm.comthat, however, Google Test only supports single-threaded usage.  Once
157813481Sgiacomo.travaglini@arm.comthread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()`
157913481Sgiacomo.travaglini@arm.comwill capture failures in the current thread only. If _statement_
158013481Sgiacomo.travaglini@arm.comcreates new threads, failures in these threads will be ignored.  If
158113481Sgiacomo.travaglini@arm.comyou want to capture failures from all threads instead, you should use
158213481Sgiacomo.travaglini@arm.comthe following macros:
158313481Sgiacomo.travaglini@arm.com
158413481Sgiacomo.travaglini@arm.com| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
158513481Sgiacomo.travaglini@arm.com|:-----------------------------------------------------------------|
158613481Sgiacomo.travaglini@arm.com| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
158713481Sgiacomo.travaglini@arm.com
158813481Sgiacomo.travaglini@arm.com# Getting the Current Test's Name #
158913481Sgiacomo.travaglini@arm.com
159013481Sgiacomo.travaglini@arm.comSometimes a function may need to know the name of the currently running test.
159113481Sgiacomo.travaglini@arm.comFor example, you may be using the `SetUp()` method of your test fixture to set
159213481Sgiacomo.travaglini@arm.comthe golden file name based on which test is running. The `::testing::TestInfo`
159313481Sgiacomo.travaglini@arm.comclass has this information:
159413481Sgiacomo.travaglini@arm.com
159513481Sgiacomo.travaglini@arm.com```
159613481Sgiacomo.travaglini@arm.comnamespace testing {
159713481Sgiacomo.travaglini@arm.com
159813481Sgiacomo.travaglini@arm.comclass TestInfo {
159913481Sgiacomo.travaglini@arm.com public:
160013481Sgiacomo.travaglini@arm.com  // Returns the test case name and the test name, respectively.
160113481Sgiacomo.travaglini@arm.com  //
160213481Sgiacomo.travaglini@arm.com  // Do NOT delete or free the return value - it's managed by the
160313481Sgiacomo.travaglini@arm.com  // TestInfo class.
160413481Sgiacomo.travaglini@arm.com  const char* test_case_name() const;
160513481Sgiacomo.travaglini@arm.com  const char* name() const;
160613481Sgiacomo.travaglini@arm.com};
160713481Sgiacomo.travaglini@arm.com
160813481Sgiacomo.travaglini@arm.com}  // namespace testing
160913481Sgiacomo.travaglini@arm.com```
161013481Sgiacomo.travaglini@arm.com
161113481Sgiacomo.travaglini@arm.com
161213481Sgiacomo.travaglini@arm.com> To obtain a `TestInfo` object for the currently running test, call
161313481Sgiacomo.travaglini@arm.com`current_test_info()` on the `UnitTest` singleton object:
161413481Sgiacomo.travaglini@arm.com
161513481Sgiacomo.travaglini@arm.com```
161613481Sgiacomo.travaglini@arm.com// Gets information about the currently running test.
161713481Sgiacomo.travaglini@arm.com// Do NOT delete the returned object - it's managed by the UnitTest class.
161813481Sgiacomo.travaglini@arm.comconst ::testing::TestInfo* const test_info =
161913481Sgiacomo.travaglini@arm.com  ::testing::UnitTest::GetInstance()->current_test_info();
162013481Sgiacomo.travaglini@arm.comprintf("We are in test %s of test case %s.\n",
162113481Sgiacomo.travaglini@arm.com       test_info->name(), test_info->test_case_name());
162213481Sgiacomo.travaglini@arm.com```
162313481Sgiacomo.travaglini@arm.com
162413481Sgiacomo.travaglini@arm.com`current_test_info()` returns a null pointer if no test is running. In
162513481Sgiacomo.travaglini@arm.comparticular, you cannot find the test case name in `TestCaseSetUp()`,
162613481Sgiacomo.travaglini@arm.com`TestCaseTearDown()` (where you know the test case name implicitly), or
162713481Sgiacomo.travaglini@arm.comfunctions called from them.
162813481Sgiacomo.travaglini@arm.com
162913481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.
163013481Sgiacomo.travaglini@arm.com
163113481Sgiacomo.travaglini@arm.com# Extending Google Test by Handling Test Events #
163213481Sgiacomo.travaglini@arm.com
163313481Sgiacomo.travaglini@arm.comGoogle Test provides an <b>event listener API</b> to let you receive
163413481Sgiacomo.travaglini@arm.comnotifications about the progress of a test program and test
163513481Sgiacomo.travaglini@arm.comfailures. The events you can listen to include the start and end of
163613481Sgiacomo.travaglini@arm.comthe test program, a test case, or a test method, among others. You may
163713481Sgiacomo.travaglini@arm.comuse this API to augment or replace the standard console output,
163813481Sgiacomo.travaglini@arm.comreplace the XML output, or provide a completely different form of
163913481Sgiacomo.travaglini@arm.comoutput, such as a GUI or a database. You can also use test events as
164013481Sgiacomo.travaglini@arm.comcheckpoints to implement a resource leak checker, for example.
164113481Sgiacomo.travaglini@arm.com
164213481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac; since v1.4.0.
164313481Sgiacomo.travaglini@arm.com
164413481Sgiacomo.travaglini@arm.com## Defining Event Listeners ##
164513481Sgiacomo.travaglini@arm.com
164613481Sgiacomo.travaglini@arm.comTo define a event listener, you subclass either
164713481Sgiacomo.travaglini@arm.com[testing::TestEventListener](../include/gtest/gtest.h#L855)
164813481Sgiacomo.travaglini@arm.comor [testing::EmptyTestEventListener](../include/gtest/gtest.h#L905).
164913481Sgiacomo.travaglini@arm.comThe former is an (abstract) interface, where <i>each pure virtual method<br>
165013481Sgiacomo.travaglini@arm.comcan be overridden to handle a test event</i> (For example, when a test
165113481Sgiacomo.travaglini@arm.comstarts, the `OnTestStart()` method will be called.). The latter provides
165213481Sgiacomo.travaglini@arm.coman empty implementation of all methods in the interface, such that a
165313481Sgiacomo.travaglini@arm.comsubclass only needs to override the methods it cares about.
165413481Sgiacomo.travaglini@arm.com
165513481Sgiacomo.travaglini@arm.comWhen an event is fired, its context is passed to the handler function
165613481Sgiacomo.travaglini@arm.comas an argument. The following argument types are used:
165713481Sgiacomo.travaglini@arm.com  * [UnitTest](../include/gtest/gtest.h#L1007) reflects the state of the entire test program,
165813481Sgiacomo.travaglini@arm.com  * [TestCase](../include/gtest/gtest.h#L689) has information about a test case, which can contain one or more tests,
165913481Sgiacomo.travaglini@arm.com  * [TestInfo](../include/gtest/gtest.h#L599) contains the state of a test, and
166013481Sgiacomo.travaglini@arm.com  * [TestPartResult](../include/gtest/gtest-test-part.h#L42) represents the result of a test assertion.
166113481Sgiacomo.travaglini@arm.com
166213481Sgiacomo.travaglini@arm.comAn event handler function can examine the argument it receives to find
166313481Sgiacomo.travaglini@arm.comout interesting information about the event and the test program's
166413481Sgiacomo.travaglini@arm.comstate.  Here's an example:
166513481Sgiacomo.travaglini@arm.com
166613481Sgiacomo.travaglini@arm.com```
166713481Sgiacomo.travaglini@arm.com  class MinimalistPrinter : public ::testing::EmptyTestEventListener {
166813481Sgiacomo.travaglini@arm.com    // Called before a test starts.
166913481Sgiacomo.travaglini@arm.com    virtual void OnTestStart(const ::testing::TestInfo& test_info) {
167013481Sgiacomo.travaglini@arm.com      printf("*** Test %s.%s starting.\n",
167113481Sgiacomo.travaglini@arm.com             test_info.test_case_name(), test_info.name());
167213481Sgiacomo.travaglini@arm.com    }
167313481Sgiacomo.travaglini@arm.com
167413481Sgiacomo.travaglini@arm.com    // Called after a failed assertion or a SUCCEED() invocation.
167513481Sgiacomo.travaglini@arm.com    virtual void OnTestPartResult(
167613481Sgiacomo.travaglini@arm.com        const ::testing::TestPartResult& test_part_result) {
167713481Sgiacomo.travaglini@arm.com      printf("%s in %s:%d\n%s\n",
167813481Sgiacomo.travaglini@arm.com             test_part_result.failed() ? "*** Failure" : "Success",
167913481Sgiacomo.travaglini@arm.com             test_part_result.file_name(),
168013481Sgiacomo.travaglini@arm.com             test_part_result.line_number(),
168113481Sgiacomo.travaglini@arm.com             test_part_result.summary());
168213481Sgiacomo.travaglini@arm.com    }
168313481Sgiacomo.travaglini@arm.com
168413481Sgiacomo.travaglini@arm.com    // Called after a test ends.
168513481Sgiacomo.travaglini@arm.com    virtual void OnTestEnd(const ::testing::TestInfo& test_info) {
168613481Sgiacomo.travaglini@arm.com      printf("*** Test %s.%s ending.\n",
168713481Sgiacomo.travaglini@arm.com             test_info.test_case_name(), test_info.name());
168813481Sgiacomo.travaglini@arm.com    }
168913481Sgiacomo.travaglini@arm.com  };
169013481Sgiacomo.travaglini@arm.com```
169113481Sgiacomo.travaglini@arm.com
169213481Sgiacomo.travaglini@arm.com## Using Event Listeners ##
169313481Sgiacomo.travaglini@arm.com
169413481Sgiacomo.travaglini@arm.comTo use the event listener you have defined, add an instance of it to
169513481Sgiacomo.travaglini@arm.comthe Google Test event listener list (represented by class
169613481Sgiacomo.travaglini@arm.com[TestEventListeners](../include/gtest/gtest.h#L929)
169713481Sgiacomo.travaglini@arm.com- note the "s" at the end of the name) in your
169813481Sgiacomo.travaglini@arm.com`main()` function, before calling `RUN_ALL_TESTS()`:
169913481Sgiacomo.travaglini@arm.com```
170013481Sgiacomo.travaglini@arm.comint main(int argc, char** argv) {
170113481Sgiacomo.travaglini@arm.com  ::testing::InitGoogleTest(&argc, argv);
170213481Sgiacomo.travaglini@arm.com  // Gets hold of the event listener list.
170313481Sgiacomo.travaglini@arm.com  ::testing::TestEventListeners& listeners =
170413481Sgiacomo.travaglini@arm.com      ::testing::UnitTest::GetInstance()->listeners();
170513481Sgiacomo.travaglini@arm.com  // Adds a listener to the end.  Google Test takes the ownership.
170613481Sgiacomo.travaglini@arm.com  listeners.Append(new MinimalistPrinter);
170713481Sgiacomo.travaglini@arm.com  return RUN_ALL_TESTS();
170813481Sgiacomo.travaglini@arm.com}
170913481Sgiacomo.travaglini@arm.com```
171013481Sgiacomo.travaglini@arm.com
171113481Sgiacomo.travaglini@arm.comThere's only one problem: the default test result printer is still in
171213481Sgiacomo.travaglini@arm.comeffect, so its output will mingle with the output from your minimalist
171313481Sgiacomo.travaglini@arm.comprinter. To suppress the default printer, just release it from the
171413481Sgiacomo.travaglini@arm.comevent listener list and delete it. You can do so by adding one line:
171513481Sgiacomo.travaglini@arm.com```
171613481Sgiacomo.travaglini@arm.com  ...
171713481Sgiacomo.travaglini@arm.com  delete listeners.Release(listeners.default_result_printer());
171813481Sgiacomo.travaglini@arm.com  listeners.Append(new MinimalistPrinter);
171913481Sgiacomo.travaglini@arm.com  return RUN_ALL_TESTS();
172013481Sgiacomo.travaglini@arm.com```
172113481Sgiacomo.travaglini@arm.com
172213481Sgiacomo.travaglini@arm.comNow, sit back and enjoy a completely different output from your
172313481Sgiacomo.travaglini@arm.comtests. For more details, you can read this
172413481Sgiacomo.travaglini@arm.com[sample](../samples/sample9_unittest.cc).
172513481Sgiacomo.travaglini@arm.com
172613481Sgiacomo.travaglini@arm.comYou may append more than one listener to the list. When an `On*Start()`
172713481Sgiacomo.travaglini@arm.comor `OnTestPartResult()` event is fired, the listeners will receive it in
172813481Sgiacomo.travaglini@arm.comthe order they appear in the list (since new listeners are added to
172913481Sgiacomo.travaglini@arm.comthe end of the list, the default text printer and the default XML
173013481Sgiacomo.travaglini@arm.comgenerator will receive the event first). An `On*End()` event will be
173113481Sgiacomo.travaglini@arm.comreceived by the listeners in the _reverse_ order. This allows output by
173213481Sgiacomo.travaglini@arm.comlisteners added later to be framed by output from listeners added
173313481Sgiacomo.travaglini@arm.comearlier.
173413481Sgiacomo.travaglini@arm.com
173513481Sgiacomo.travaglini@arm.com## Generating Failures in Listeners ##
173613481Sgiacomo.travaglini@arm.com
173713481Sgiacomo.travaglini@arm.comYou may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`,
173813481Sgiacomo.travaglini@arm.com`FAIL()`, etc) when processing an event. There are some restrictions:
173913481Sgiacomo.travaglini@arm.com
174013481Sgiacomo.travaglini@arm.com  1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively).
174113481Sgiacomo.travaglini@arm.com  1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure.
174213481Sgiacomo.travaglini@arm.com
174313481Sgiacomo.travaglini@arm.comWhen you add listeners to the listener list, you should put listeners
174413481Sgiacomo.travaglini@arm.comthat handle `OnTestPartResult()` _before_ listeners that can generate
174513481Sgiacomo.travaglini@arm.comfailures. This ensures that failures generated by the latter are
174613481Sgiacomo.travaglini@arm.comattributed to the right test by the former.
174713481Sgiacomo.travaglini@arm.com
174813481Sgiacomo.travaglini@arm.comWe have a sample of failure-raising listener
174913481Sgiacomo.travaglini@arm.com[here](../samples/sample10_unittest.cc).
175013481Sgiacomo.travaglini@arm.com
175113481Sgiacomo.travaglini@arm.com# Running Test Programs: Advanced Options #
175213481Sgiacomo.travaglini@arm.com
175313481Sgiacomo.travaglini@arm.comGoogle Test test programs are ordinary executables. Once built, you can run
175413481Sgiacomo.travaglini@arm.comthem directly and affect their behavior via the following environment variables
175513481Sgiacomo.travaglini@arm.comand/or command line flags. For the flags to work, your programs must call
175613481Sgiacomo.travaglini@arm.com`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
175713481Sgiacomo.travaglini@arm.com
175813481Sgiacomo.travaglini@arm.comTo see a list of supported flags and their usage, please run your test
175913481Sgiacomo.travaglini@arm.comprogram with the `--help` flag.  You can also use `-h`, `-?`, or `/?`
176013481Sgiacomo.travaglini@arm.comfor short.  This feature is added in version 1.3.0.
176113481Sgiacomo.travaglini@arm.com
176213481Sgiacomo.travaglini@arm.comIf an option is specified both by an environment variable and by a
176313481Sgiacomo.travaglini@arm.comflag, the latter takes precedence.  Most of the options can also be
176413481Sgiacomo.travaglini@arm.comset/read in code: to access the value of command line flag
176513481Sgiacomo.travaglini@arm.com`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`.  A common pattern is
176613481Sgiacomo.travaglini@arm.comto set the value of a flag before calling `::testing::InitGoogleTest()`
176713481Sgiacomo.travaglini@arm.comto change the default value of the flag:
176813481Sgiacomo.travaglini@arm.com```
176913481Sgiacomo.travaglini@arm.comint main(int argc, char** argv) {
177013481Sgiacomo.travaglini@arm.com  // Disables elapsed time by default.
177113481Sgiacomo.travaglini@arm.com  ::testing::GTEST_FLAG(print_time) = false;
177213481Sgiacomo.travaglini@arm.com
177313481Sgiacomo.travaglini@arm.com  // This allows the user to override the flag on the command line.
177413481Sgiacomo.travaglini@arm.com  ::testing::InitGoogleTest(&argc, argv);
177513481Sgiacomo.travaglini@arm.com
177613481Sgiacomo.travaglini@arm.com  return RUN_ALL_TESTS();
177713481Sgiacomo.travaglini@arm.com}
177813481Sgiacomo.travaglini@arm.com```
177913481Sgiacomo.travaglini@arm.com
178013481Sgiacomo.travaglini@arm.com## Selecting Tests ##
178113481Sgiacomo.travaglini@arm.com
178213481Sgiacomo.travaglini@arm.comThis section shows various options for choosing which tests to run.
178313481Sgiacomo.travaglini@arm.com
178413481Sgiacomo.travaglini@arm.com### Listing Test Names ###
178513481Sgiacomo.travaglini@arm.com
178613481Sgiacomo.travaglini@arm.comSometimes it is necessary to list the available tests in a program before
178713481Sgiacomo.travaglini@arm.comrunning them so that a filter may be applied if needed. Including the flag
178813481Sgiacomo.travaglini@arm.com`--gtest_list_tests` overrides all other flags and lists tests in the following
178913481Sgiacomo.travaglini@arm.comformat:
179013481Sgiacomo.travaglini@arm.com```
179113481Sgiacomo.travaglini@arm.comTestCase1.
179213481Sgiacomo.travaglini@arm.com  TestName1
179313481Sgiacomo.travaglini@arm.com  TestName2
179413481Sgiacomo.travaglini@arm.comTestCase2.
179513481Sgiacomo.travaglini@arm.com  TestName
179613481Sgiacomo.travaglini@arm.com```
179713481Sgiacomo.travaglini@arm.com
179813481Sgiacomo.travaglini@arm.comNone of the tests listed are actually run if the flag is provided. There is no
179913481Sgiacomo.travaglini@arm.comcorresponding environment variable for this flag.
180013481Sgiacomo.travaglini@arm.com
180113481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.
180213481Sgiacomo.travaglini@arm.com
180313481Sgiacomo.travaglini@arm.com### Running a Subset of the Tests ###
180413481Sgiacomo.travaglini@arm.com
180513481Sgiacomo.travaglini@arm.comBy default, a Google Test program runs all tests the user has defined.
180613481Sgiacomo.travaglini@arm.comSometimes, you want to run only a subset of the tests (e.g. for debugging or
180713481Sgiacomo.travaglini@arm.comquickly verifying a change). If you set the `GTEST_FILTER` environment variable
180813481Sgiacomo.travaglini@arm.comor the `--gtest_filter` flag to a filter string, Google Test will only run the
180913481Sgiacomo.travaglini@arm.comtests whose full names (in the form of `TestCaseName.TestName`) match the
181013481Sgiacomo.travaglini@arm.comfilter.
181113481Sgiacomo.travaglini@arm.com
181213481Sgiacomo.travaglini@arm.comThe format of a filter is a '`:`'-separated list of wildcard patterns (called
181313481Sgiacomo.travaglini@arm.comthe positive patterns) optionally followed by a '`-`' and another
181413481Sgiacomo.travaglini@arm.com'`:`'-separated pattern list (called the negative patterns). A test matches the
181513481Sgiacomo.travaglini@arm.comfilter if and only if it matches any of the positive patterns but does not
181613481Sgiacomo.travaglini@arm.commatch any of the negative patterns.
181713481Sgiacomo.travaglini@arm.com
181813481Sgiacomo.travaglini@arm.comA pattern may contain `'*'` (matches any string) or `'?'` (matches any single
181913481Sgiacomo.travaglini@arm.comcharacter). For convenience, the filter `'*-NegativePatterns'` can be also
182013481Sgiacomo.travaglini@arm.comwritten as `'-NegativePatterns'`.
182113481Sgiacomo.travaglini@arm.com
182213481Sgiacomo.travaglini@arm.comFor example:
182313481Sgiacomo.travaglini@arm.com
182413481Sgiacomo.travaglini@arm.com  * `./foo_test` Has no flag, and thus runs all its tests.
182513481Sgiacomo.travaglini@arm.com  * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value.
182613481Sgiacomo.travaglini@arm.com  * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`.
182713481Sgiacomo.travaglini@arm.com  * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`.
182813481Sgiacomo.travaglini@arm.com  * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests.
182913481Sgiacomo.travaglini@arm.com  * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`.
183013481Sgiacomo.travaglini@arm.com
183113481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.
183213481Sgiacomo.travaglini@arm.com
183313481Sgiacomo.travaglini@arm.com### Temporarily Disabling Tests ###
183413481Sgiacomo.travaglini@arm.com
183513481Sgiacomo.travaglini@arm.comIf you have a broken test that you cannot fix right away, you can add the
183613481Sgiacomo.travaglini@arm.com`DISABLED_` prefix to its name. This will exclude it from execution. This is
183713481Sgiacomo.travaglini@arm.combetter than commenting out the code or using `#if 0`, as disabled tests are
183813481Sgiacomo.travaglini@arm.comstill compiled (and thus won't rot).
183913481Sgiacomo.travaglini@arm.com
184013481Sgiacomo.travaglini@arm.comIf you need to disable all tests in a test case, you can either add `DISABLED_`
184113481Sgiacomo.travaglini@arm.comto the front of the name of each test, or alternatively add it to the front of
184213481Sgiacomo.travaglini@arm.comthe test case name.
184313481Sgiacomo.travaglini@arm.com
184413481Sgiacomo.travaglini@arm.comFor example, the following tests won't be run by Google Test, even though they
184513481Sgiacomo.travaglini@arm.comwill still be compiled:
184613481Sgiacomo.travaglini@arm.com
184713481Sgiacomo.travaglini@arm.com```
184813481Sgiacomo.travaglini@arm.com// Tests that Foo does Abc.
184913481Sgiacomo.travaglini@arm.comTEST(FooTest, DISABLED_DoesAbc) { ... }
185013481Sgiacomo.travaglini@arm.com
185113481Sgiacomo.travaglini@arm.comclass DISABLED_BarTest : public ::testing::Test { ... };
185213481Sgiacomo.travaglini@arm.com
185313481Sgiacomo.travaglini@arm.com// Tests that Bar does Xyz.
185413481Sgiacomo.travaglini@arm.comTEST_F(DISABLED_BarTest, DoesXyz) { ... }
185513481Sgiacomo.travaglini@arm.com```
185613481Sgiacomo.travaglini@arm.com
185713481Sgiacomo.travaglini@arm.com_Note:_ This feature should only be used for temporary pain-relief. You still
185813481Sgiacomo.travaglini@arm.comhave to fix the disabled tests at a later date. As a reminder, Google Test will
185913481Sgiacomo.travaglini@arm.comprint a banner warning you if a test program contains any disabled tests.
186013481Sgiacomo.travaglini@arm.com
186113481Sgiacomo.travaglini@arm.com_Tip:_ You can easily count the number of disabled tests you have
186213481Sgiacomo.travaglini@arm.comusing `grep`. This number can be used as a metric for improving your
186313481Sgiacomo.travaglini@arm.comtest quality.
186413481Sgiacomo.travaglini@arm.com
186513481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.
186613481Sgiacomo.travaglini@arm.com
186713481Sgiacomo.travaglini@arm.com### Temporarily Enabling Disabled Tests ###
186813481Sgiacomo.travaglini@arm.com
186913481Sgiacomo.travaglini@arm.comTo include [disabled tests](#temporarily-disabling-tests) in test
187013481Sgiacomo.travaglini@arm.comexecution, just invoke the test program with the
187113481Sgiacomo.travaglini@arm.com`--gtest_also_run_disabled_tests` flag or set the
187213481Sgiacomo.travaglini@arm.com`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other
187313481Sgiacomo.travaglini@arm.comthan `0`.  You can combine this with the
187413481Sgiacomo.travaglini@arm.com[--gtest\_filter](#running-a-subset-of-the-tests) flag to further select
187513481Sgiacomo.travaglini@arm.comwhich disabled tests to run.
187613481Sgiacomo.travaglini@arm.com
187713481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac; since version 1.3.0.
187813481Sgiacomo.travaglini@arm.com
187913481Sgiacomo.travaglini@arm.com## Repeating the Tests ##
188013481Sgiacomo.travaglini@arm.com
188113481Sgiacomo.travaglini@arm.comOnce in a while you'll run into a test whose result is hit-or-miss. Perhaps it
188213481Sgiacomo.travaglini@arm.comwill fail only 1% of the time, making it rather hard to reproduce the bug under
188313481Sgiacomo.travaglini@arm.coma debugger. This can be a major source of frustration.
188413481Sgiacomo.travaglini@arm.com
188513481Sgiacomo.travaglini@arm.comThe `--gtest_repeat` flag allows you to repeat all (or selected) test methods
188613481Sgiacomo.travaglini@arm.comin a program many times. Hopefully, a flaky test will eventually fail and give
188713481Sgiacomo.travaglini@arm.comyou a chance to debug. Here's how to use it:
188813481Sgiacomo.travaglini@arm.com
188913481Sgiacomo.travaglini@arm.com| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. |
189013481Sgiacomo.travaglini@arm.com|:---------------------------------|:--------------------------------------------------------|
189113481Sgiacomo.travaglini@arm.com| `$ foo_test --gtest_repeat=-1`   | A negative count means repeating forever.               |
189213481Sgiacomo.travaglini@arm.com| `$ 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. |
189313481Sgiacomo.travaglini@arm.com| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. |
189413481Sgiacomo.travaglini@arm.com
189513481Sgiacomo.travaglini@arm.comIf your test program contains global set-up/tear-down code registered
189613481Sgiacomo.travaglini@arm.comusing `AddGlobalTestEnvironment()`, it will be repeated in each
189713481Sgiacomo.travaglini@arm.comiteration as well, as the flakiness may be in it. You can also specify
189813481Sgiacomo.travaglini@arm.comthe repeat count by setting the `GTEST_REPEAT` environment variable.
189913481Sgiacomo.travaglini@arm.com
190013481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.
190113481Sgiacomo.travaglini@arm.com
190213481Sgiacomo.travaglini@arm.com## Shuffling the Tests ##
190313481Sgiacomo.travaglini@arm.com
190413481Sgiacomo.travaglini@arm.comYou can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`
190513481Sgiacomo.travaglini@arm.comenvironment variable to `1`) to run the tests in a program in a random
190613481Sgiacomo.travaglini@arm.comorder. This helps to reveal bad dependencies between tests.
190713481Sgiacomo.travaglini@arm.com
190813481Sgiacomo.travaglini@arm.comBy default, Google Test uses a random seed calculated from the current
190913481Sgiacomo.travaglini@arm.comtime. Therefore you'll get a different order every time. The console
191013481Sgiacomo.travaglini@arm.comoutput includes the random seed value, such that you can reproduce an
191113481Sgiacomo.travaglini@arm.comorder-related test failure later. To specify the random seed
191213481Sgiacomo.travaglini@arm.comexplicitly, use the `--gtest_random_seed=SEED` flag (or set the
191313481Sgiacomo.travaglini@arm.com`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer
191413481Sgiacomo.travaglini@arm.combetween 0 and 99999. The seed value 0 is special: it tells Google Test
191513481Sgiacomo.travaglini@arm.comto do the default behavior of calculating the seed from the current
191613481Sgiacomo.travaglini@arm.comtime.
191713481Sgiacomo.travaglini@arm.com
191813481Sgiacomo.travaglini@arm.comIf you combine this with `--gtest_repeat=N`, Google Test will pick a
191913481Sgiacomo.travaglini@arm.comdifferent random seed and re-shuffle the tests in each iteration.
192013481Sgiacomo.travaglini@arm.com
192113481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac; since v1.4.0.
192213481Sgiacomo.travaglini@arm.com
192313481Sgiacomo.travaglini@arm.com## Controlling Test Output ##
192413481Sgiacomo.travaglini@arm.com
192513481Sgiacomo.travaglini@arm.comThis section teaches how to tweak the way test results are reported.
192613481Sgiacomo.travaglini@arm.com
192713481Sgiacomo.travaglini@arm.com### Colored Terminal Output ###
192813481Sgiacomo.travaglini@arm.com
192913481Sgiacomo.travaglini@arm.comGoogle Test can use colors in its terminal output to make it easier to spot
193013481Sgiacomo.travaglini@arm.comthe separation between tests, and whether tests passed.
193113481Sgiacomo.travaglini@arm.com
193213481Sgiacomo.travaglini@arm.comYou can set the GTEST\_COLOR environment variable or set the `--gtest_color`
193313481Sgiacomo.travaglini@arm.comcommand line flag to `yes`, `no`, or `auto` (the default) to enable colors,
193413481Sgiacomo.travaglini@arm.comdisable colors, or let Google Test decide. When the value is `auto`, Google
193513481Sgiacomo.travaglini@arm.comTest will use colors if and only if the output goes to a terminal and (on
193613481Sgiacomo.travaglini@arm.comnon-Windows platforms) the `TERM` environment variable is set to `xterm` or
193713481Sgiacomo.travaglini@arm.com`xterm-color`.
193813481Sgiacomo.travaglini@arm.com
193913481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.
194013481Sgiacomo.travaglini@arm.com
194113481Sgiacomo.travaglini@arm.com### Suppressing the Elapsed Time ###
194213481Sgiacomo.travaglini@arm.com
194313481Sgiacomo.travaglini@arm.comBy default, Google Test prints the time it takes to run each test.  To
194413481Sgiacomo.travaglini@arm.comsuppress that, run the test program with the `--gtest_print_time=0`
194513481Sgiacomo.travaglini@arm.comcommand line flag.  Setting the `GTEST_PRINT_TIME` environment
194613481Sgiacomo.travaglini@arm.comvariable to `0` has the same effect.
194713481Sgiacomo.travaglini@arm.com
194813481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.  (In Google Test 1.3.0 and lower,
194913481Sgiacomo.travaglini@arm.comthe default behavior is that the elapsed time is **not** printed.)
195013481Sgiacomo.travaglini@arm.com
195113481Sgiacomo.travaglini@arm.com### Generating an XML Report ###
195213481Sgiacomo.travaglini@arm.com
195313481Sgiacomo.travaglini@arm.comGoogle Test can emit a detailed XML report to a file in addition to its normal
195413481Sgiacomo.travaglini@arm.comtextual output. The report contains the duration of each test, and thus can
195513481Sgiacomo.travaglini@arm.comhelp you identify slow tests.
195613481Sgiacomo.travaglini@arm.com
195713481Sgiacomo.travaglini@arm.comTo generate the XML report, set the `GTEST_OUTPUT` environment variable or the
195813481Sgiacomo.travaglini@arm.com`--gtest_output` flag to the string `"xml:_path_to_output_file_"`, which will
195913481Sgiacomo.travaglini@arm.comcreate the file at the given location. You can also just use the string
196013481Sgiacomo.travaglini@arm.com`"xml"`, in which case the output can be found in the `test_detail.xml` file in
196113481Sgiacomo.travaglini@arm.comthe current directory.
196213481Sgiacomo.travaglini@arm.com
196313481Sgiacomo.travaglini@arm.comIf you specify a directory (for example, `"xml:output/directory/"` on Linux or
196413481Sgiacomo.travaglini@arm.com`"xml:output\directory\"` on Windows), Google Test will create the XML file in
196513481Sgiacomo.travaglini@arm.comthat directory, named after the test executable (e.g. `foo_test.xml` for test
196613481Sgiacomo.travaglini@arm.comprogram `foo_test` or `foo_test.exe`). If the file already exists (perhaps left
196713481Sgiacomo.travaglini@arm.comover from a previous run), Google Test will pick a different name (e.g.
196813481Sgiacomo.travaglini@arm.com`foo_test_1.xml`) to avoid overwriting it.
196913481Sgiacomo.travaglini@arm.com
197013481Sgiacomo.travaglini@arm.comThe report uses the format described here.  It is based on the
197113481Sgiacomo.travaglini@arm.com`junitreport` Ant task and can be parsed by popular continuous build
197213481Sgiacomo.travaglini@arm.comsystems like [Jenkins](http://jenkins-ci.org/). Since that format
197313481Sgiacomo.travaglini@arm.comwas originally intended for Java, a little interpretation is required
197413481Sgiacomo.travaglini@arm.comto make it apply to Google Test tests, as shown here:
197513481Sgiacomo.travaglini@arm.com
197613481Sgiacomo.travaglini@arm.com```
197713481Sgiacomo.travaglini@arm.com<testsuites name="AllTests" ...>
197813481Sgiacomo.travaglini@arm.com  <testsuite name="test_case_name" ...>
197913481Sgiacomo.travaglini@arm.com    <testcase name="test_name" ...>
198013481Sgiacomo.travaglini@arm.com      <failure message="..."/>
198113481Sgiacomo.travaglini@arm.com      <failure message="..."/>
198213481Sgiacomo.travaglini@arm.com      <failure message="..."/>
198313481Sgiacomo.travaglini@arm.com    </testcase>
198413481Sgiacomo.travaglini@arm.com  </testsuite>
198513481Sgiacomo.travaglini@arm.com</testsuites>
198613481Sgiacomo.travaglini@arm.com```
198713481Sgiacomo.travaglini@arm.com
198813481Sgiacomo.travaglini@arm.com  * The root `<testsuites>` element corresponds to the entire test program.
198913481Sgiacomo.travaglini@arm.com  * `<testsuite>` elements correspond to Google Test test cases.
199013481Sgiacomo.travaglini@arm.com  * `<testcase>` elements correspond to Google Test test functions.
199113481Sgiacomo.travaglini@arm.com
199213481Sgiacomo.travaglini@arm.comFor instance, the following program
199313481Sgiacomo.travaglini@arm.com
199413481Sgiacomo.travaglini@arm.com```
199513481Sgiacomo.travaglini@arm.comTEST(MathTest, Addition) { ... }
199613481Sgiacomo.travaglini@arm.comTEST(MathTest, Subtraction) { ... }
199713481Sgiacomo.travaglini@arm.comTEST(LogicTest, NonContradiction) { ... }
199813481Sgiacomo.travaglini@arm.com```
199913481Sgiacomo.travaglini@arm.com
200013481Sgiacomo.travaglini@arm.comcould generate this report:
200113481Sgiacomo.travaglini@arm.com
200213481Sgiacomo.travaglini@arm.com```
200313481Sgiacomo.travaglini@arm.com<?xml version="1.0" encoding="UTF-8"?>
200413481Sgiacomo.travaglini@arm.com<testsuites tests="3" failures="1" errors="0" time="35" name="AllTests">
200513481Sgiacomo.travaglini@arm.com  <testsuite name="MathTest" tests="2" failures="1" errors="0" time="15">
200613481Sgiacomo.travaglini@arm.com    <testcase name="Addition" status="run" time="7" classname="">
200713481Sgiacomo.travaglini@arm.com      <failure message="Value of: add(1, 1)&#x0A; Actual: 3&#x0A;Expected: 2" type=""/>
200813481Sgiacomo.travaglini@arm.com      <failure message="Value of: add(1, -1)&#x0A; Actual: 1&#x0A;Expected: 0" type=""/>
200913481Sgiacomo.travaglini@arm.com    </testcase>
201013481Sgiacomo.travaglini@arm.com    <testcase name="Subtraction" status="run" time="5" classname="">
201113481Sgiacomo.travaglini@arm.com    </testcase>
201213481Sgiacomo.travaglini@arm.com  </testsuite>
201313481Sgiacomo.travaglini@arm.com  <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5">
201413481Sgiacomo.travaglini@arm.com    <testcase name="NonContradiction" status="run" time="5" classname="">
201513481Sgiacomo.travaglini@arm.com    </testcase>
201613481Sgiacomo.travaglini@arm.com  </testsuite>
201713481Sgiacomo.travaglini@arm.com</testsuites>
201813481Sgiacomo.travaglini@arm.com```
201913481Sgiacomo.travaglini@arm.com
202013481Sgiacomo.travaglini@arm.comThings to note:
202113481Sgiacomo.travaglini@arm.com
202213481Sgiacomo.travaglini@arm.com  * 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.
202313481Sgiacomo.travaglini@arm.com  * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds.
202413481Sgiacomo.travaglini@arm.com  * Each `<failure>` element corresponds to a single failed Google Test assertion.
202513481Sgiacomo.travaglini@arm.com  * 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.
202613481Sgiacomo.travaglini@arm.com
202713481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.
202813481Sgiacomo.travaglini@arm.com
202913481Sgiacomo.travaglini@arm.com## Controlling How Failures Are Reported ##
203013481Sgiacomo.travaglini@arm.com
203113481Sgiacomo.travaglini@arm.com### Turning Assertion Failures into Break-Points ###
203213481Sgiacomo.travaglini@arm.com
203313481Sgiacomo.travaglini@arm.comWhen running test programs under a debugger, it's very convenient if the
203413481Sgiacomo.travaglini@arm.comdebugger can catch an assertion failure and automatically drop into interactive
203513481Sgiacomo.travaglini@arm.commode. Google Test's _break-on-failure_ mode supports this behavior.
203613481Sgiacomo.travaglini@arm.com
203713481Sgiacomo.travaglini@arm.comTo enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value
203813481Sgiacomo.travaglini@arm.comother than `0` . Alternatively, you can use the `--gtest_break_on_failure`
203913481Sgiacomo.travaglini@arm.comcommand line flag.
204013481Sgiacomo.travaglini@arm.com
204113481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac.
204213481Sgiacomo.travaglini@arm.com
204313481Sgiacomo.travaglini@arm.com### Disabling Catching Test-Thrown Exceptions ###
204413481Sgiacomo.travaglini@arm.com
204513481Sgiacomo.travaglini@arm.comGoogle Test can be used either with or without exceptions enabled.  If
204613481Sgiacomo.travaglini@arm.coma test throws a C++ exception or (on Windows) a structured exception
204713481Sgiacomo.travaglini@arm.com(SEH), by default Google Test catches it, reports it as a test
204813481Sgiacomo.travaglini@arm.comfailure, and continues with the next test method.  This maximizes the
204913481Sgiacomo.travaglini@arm.comcoverage of a test run.  Also, on Windows an uncaught exception will
205013481Sgiacomo.travaglini@arm.comcause a pop-up window, so catching the exceptions allows you to run
205113481Sgiacomo.travaglini@arm.comthe tests automatically.
205213481Sgiacomo.travaglini@arm.com
205313481Sgiacomo.travaglini@arm.comWhen debugging the test failures, however, you may instead want the
205413481Sgiacomo.travaglini@arm.comexceptions to be handled by the debugger, such that you can examine
205513481Sgiacomo.travaglini@arm.comthe call stack when an exception is thrown.  To achieve that, set the
205613481Sgiacomo.travaglini@arm.com`GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the
205713481Sgiacomo.travaglini@arm.com`--gtest_catch_exceptions=0` flag when running the tests.
205813481Sgiacomo.travaglini@arm.com
205913481Sgiacomo.travaglini@arm.com**Availability**: Linux, Windows, Mac.
206013481Sgiacomo.travaglini@arm.com
206113481Sgiacomo.travaglini@arm.com### Letting Another Testing Framework Drive ###
206213481Sgiacomo.travaglini@arm.com
206313481Sgiacomo.travaglini@arm.comIf you work on a project that has already been using another testing
206413481Sgiacomo.travaglini@arm.comframework and is not ready to completely switch to Google Test yet,
206513481Sgiacomo.travaglini@arm.comyou can get much of Google Test's benefit by using its assertions in
206613481Sgiacomo.travaglini@arm.comyour existing tests.  Just change your `main()` function to look
206713481Sgiacomo.travaglini@arm.comlike:
206813481Sgiacomo.travaglini@arm.com
206913481Sgiacomo.travaglini@arm.com```
207013481Sgiacomo.travaglini@arm.com#include "gtest/gtest.h"
207113481Sgiacomo.travaglini@arm.com
207213481Sgiacomo.travaglini@arm.comint main(int argc, char** argv) {
207313481Sgiacomo.travaglini@arm.com  ::testing::GTEST_FLAG(throw_on_failure) = true;
207413481Sgiacomo.travaglini@arm.com  // Important: Google Test must be initialized.
207513481Sgiacomo.travaglini@arm.com  ::testing::InitGoogleTest(&argc, argv);
207613481Sgiacomo.travaglini@arm.com
207713481Sgiacomo.travaglini@arm.com  ... whatever your existing testing framework requires ...
207813481Sgiacomo.travaglini@arm.com}
207913481Sgiacomo.travaglini@arm.com```
208013481Sgiacomo.travaglini@arm.com
208113481Sgiacomo.travaglini@arm.comWith that, you can use Google Test assertions in addition to the
208213481Sgiacomo.travaglini@arm.comnative assertions your testing framework provides, for example:
208313481Sgiacomo.travaglini@arm.com
208413481Sgiacomo.travaglini@arm.com```
208513481Sgiacomo.travaglini@arm.comvoid TestFooDoesBar() {
208613481Sgiacomo.travaglini@arm.com  Foo foo;
208713481Sgiacomo.travaglini@arm.com  EXPECT_LE(foo.Bar(1), 100);     // A Google Test assertion.
208813481Sgiacomo.travaglini@arm.com  CPPUNIT_ASSERT(foo.IsEmpty());  // A native assertion.
208913481Sgiacomo.travaglini@arm.com}
209013481Sgiacomo.travaglini@arm.com```
209113481Sgiacomo.travaglini@arm.com
209213481Sgiacomo.travaglini@arm.comIf a Google Test assertion fails, it will print an error message and
209313481Sgiacomo.travaglini@arm.comthrow an exception, which will be treated as a failure by your host
209413481Sgiacomo.travaglini@arm.comtesting framework.  If you compile your code with exceptions disabled,
209513481Sgiacomo.travaglini@arm.coma failed Google Test assertion will instead exit your program with a
209613481Sgiacomo.travaglini@arm.comnon-zero code, which will also signal a test failure to your test
209713481Sgiacomo.travaglini@arm.comrunner.
209813481Sgiacomo.travaglini@arm.com
209913481Sgiacomo.travaglini@arm.comIf you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in
210013481Sgiacomo.travaglini@arm.comyour `main()`, you can alternatively enable this feature by specifying
210113481Sgiacomo.travaglini@arm.comthe `--gtest_throw_on_failure` flag on the command-line or setting the
210213481Sgiacomo.travaglini@arm.com`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value.
210313481Sgiacomo.travaglini@arm.com
210413481Sgiacomo.travaglini@arm.comDeath tests are _not_ supported when other test framework is used to organize tests.
210513481Sgiacomo.travaglini@arm.com
210613481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac; since v1.3.0.
210713481Sgiacomo.travaglini@arm.com
210813481Sgiacomo.travaglini@arm.com## Distributing Test Functions to Multiple Machines ##
210913481Sgiacomo.travaglini@arm.com
211013481Sgiacomo.travaglini@arm.comIf you have more than one machine you can use to run a test program,
211113481Sgiacomo.travaglini@arm.comyou might want to run the test functions in parallel and get the
211213481Sgiacomo.travaglini@arm.comresult faster.  We call this technique _sharding_, where each machine
211313481Sgiacomo.travaglini@arm.comis called a _shard_.
211413481Sgiacomo.travaglini@arm.com
211513481Sgiacomo.travaglini@arm.comGoogle Test is compatible with test sharding.  To take advantage of
211613481Sgiacomo.travaglini@arm.comthis feature, your test runner (not part of Google Test) needs to do
211713481Sgiacomo.travaglini@arm.comthe following:
211813481Sgiacomo.travaglini@arm.com
211913481Sgiacomo.travaglini@arm.com  1. Allocate a number of machines (shards) to run the tests.
212013481Sgiacomo.travaglini@arm.com  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.
212113481Sgiacomo.travaglini@arm.com  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]`.
212213481Sgiacomo.travaglini@arm.com  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.
212313481Sgiacomo.travaglini@arm.com  1. Wait for all shards to finish, then collect and report the results.
212413481Sgiacomo.travaglini@arm.com
212513481Sgiacomo.travaglini@arm.comYour project may have tests that were written without Google Test and
212613481Sgiacomo.travaglini@arm.comthus don't understand this protocol.  In order for your test runner to
212713481Sgiacomo.travaglini@arm.comfigure out which test supports sharding, it can set the environment
212813481Sgiacomo.travaglini@arm.comvariable `GTEST_SHARD_STATUS_FILE` to a non-existent file path.  If a
212913481Sgiacomo.travaglini@arm.comtest program supports sharding, it will create this file to
213013481Sgiacomo.travaglini@arm.comacknowledge the fact (the actual contents of the file are not
213113481Sgiacomo.travaglini@arm.comimportant at this time; although we may stick some useful information
213213481Sgiacomo.travaglini@arm.comin it in the future.); otherwise it will not create it.
213313481Sgiacomo.travaglini@arm.com
213413481Sgiacomo.travaglini@arm.comHere's an example to make it clear.  Suppose you have a test program
213513481Sgiacomo.travaglini@arm.com`foo_test` that contains the following 5 test functions:
213613481Sgiacomo.travaglini@arm.com```
213713481Sgiacomo.travaglini@arm.comTEST(A, V)
213813481Sgiacomo.travaglini@arm.comTEST(A, W)
213913481Sgiacomo.travaglini@arm.comTEST(B, X)
214013481Sgiacomo.travaglini@arm.comTEST(B, Y)
214113481Sgiacomo.travaglini@arm.comTEST(B, Z)
214213481Sgiacomo.travaglini@arm.com```
214313481Sgiacomo.travaglini@arm.comand you have 3 machines at your disposal.  To run the test functions in
214413481Sgiacomo.travaglini@arm.comparallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and
214513481Sgiacomo.travaglini@arm.comset `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively.
214613481Sgiacomo.travaglini@arm.comThen you would run the same `foo_test` on each machine.
214713481Sgiacomo.travaglini@arm.com
214813481Sgiacomo.travaglini@arm.comGoogle Test reserves the right to change how the work is distributed
214913481Sgiacomo.travaglini@arm.comacross the shards, but here's one possible scenario:
215013481Sgiacomo.travaglini@arm.com
215113481Sgiacomo.travaglini@arm.com  * Machine #0 runs `A.V` and `B.X`.
215213481Sgiacomo.travaglini@arm.com  * Machine #1 runs `A.W` and `B.Y`.
215313481Sgiacomo.travaglini@arm.com  * Machine #2 runs `B.Z`.
215413481Sgiacomo.travaglini@arm.com
215513481Sgiacomo.travaglini@arm.com_Availability:_ Linux, Windows, Mac; since version 1.3.0.
215613481Sgiacomo.travaglini@arm.com
215713481Sgiacomo.travaglini@arm.com# Fusing Google Test Source Files #
215813481Sgiacomo.travaglini@arm.com
215913481Sgiacomo.travaglini@arm.comGoogle Test's implementation consists of ~30 files (excluding its own
216013481Sgiacomo.travaglini@arm.comtests).  Sometimes you may want them to be packaged up in two files (a
216113481Sgiacomo.travaglini@arm.com`.h` and a `.cc`) instead, such that you can easily copy them to a new
216213481Sgiacomo.travaglini@arm.commachine and start hacking there.  For this we provide an experimental
216313481Sgiacomo.travaglini@arm.comPython script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0).
216413481Sgiacomo.travaglini@arm.comAssuming you have Python 2.4 or above installed on your machine, just
216513481Sgiacomo.travaglini@arm.comgo to that directory and run
216613481Sgiacomo.travaglini@arm.com```
216713481Sgiacomo.travaglini@arm.compython fuse_gtest_files.py OUTPUT_DIR
216813481Sgiacomo.travaglini@arm.com```
216913481Sgiacomo.travaglini@arm.com
217013481Sgiacomo.travaglini@arm.comand you should see an `OUTPUT_DIR` directory being created with files
217113481Sgiacomo.travaglini@arm.com`gtest/gtest.h` and `gtest/gtest-all.cc` in it.  These files contain
217213481Sgiacomo.travaglini@arm.comeverything you need to use Google Test.  Just copy them to anywhere
217313481Sgiacomo.travaglini@arm.comyou want and you are ready to write tests.  You can use the
217413481Sgiacomo.travaglini@arm.com[scripts/test/Makefile](../scripts/test/Makefile)
217513481Sgiacomo.travaglini@arm.comfile as an example on how to compile your tests against them.
217613481Sgiacomo.travaglini@arm.com
217713481Sgiacomo.travaglini@arm.com# Where to Go from Here #
217813481Sgiacomo.travaglini@arm.com
217913481Sgiacomo.travaglini@arm.comCongratulations! You've now learned more advanced Google Test tools and are
218013481Sgiacomo.travaglini@arm.comready to tackle more complex testing tasks. If you want to dive even deeper, you
218113481Sgiacomo.travaglini@arm.comcan read the [Frequently-Asked Questions](V1_7_FAQ.md).
2182