Blame googletest/docs/AdvancedGuide.md

Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
Now that you have read [Primer](Primer.md) and learned how to write tests
Packit bd1cd8
using Google Test, it's time to learn some new tricks. This document
Packit bd1cd8
will show you more assertions as well as how to construct complex
Packit bd1cd8
failure messages, propagate fatal failures, reuse and speed up your
Packit bd1cd8
test fixtures, and use various flags with your tests.
Packit bd1cd8
Packit bd1cd8
# More Assertions #
Packit bd1cd8
Packit bd1cd8
This section covers some less frequently used, but still significant,
Packit bd1cd8
assertions.
Packit bd1cd8
Packit bd1cd8
## Explicit Success and Failure ##
Packit bd1cd8
Packit bd1cd8
These three assertions do not actually test a value or expression. Instead,
Packit bd1cd8
they generate a success or failure directly. Like the macros that actually
Packit bd1cd8
perform a test, you may stream a custom failure message into the them.
Packit bd1cd8
Packit bd1cd8
| `SUCCEED();` |
Packit bd1cd8
|:-------------|
Packit bd1cd8
Packit bd1cd8
Generates a success. This does NOT make the overall test succeed. A test is
Packit bd1cd8
considered successful only if none of its assertions fail during its execution.
Packit bd1cd8
Packit bd1cd8
Note: `SUCCEED()` is purely documentary and currently doesn't generate any
Packit bd1cd8
user-visible output. However, we may add `SUCCEED()` messages to Google Test's
Packit bd1cd8
output in the future.
Packit bd1cd8
Packit bd1cd8
| `FAIL();`  | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` |
Packit bd1cd8
|:-----------|:-----------------|:------------------------------------------------------|
Packit bd1cd8
Packit bd1cd8
`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal
Packit bd1cd8
failure. These are useful when control flow, rather than a Boolean expression,
Packit bd1cd8
deteremines the test's success or failure. For example, you might want to write
Packit bd1cd8
something like:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
switch(expression) {
Packit bd1cd8
  case 1: ... some checks ...
Packit bd1cd8
  case 2: ... some other checks
Packit bd1cd8
  ...
Packit bd1cd8
  default: FAIL() << "We shouldn't get here.";
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Note: you can only use `FAIL()` in functions that return `void`. See the [Assertion Placement section](#assertion-placement) for more information.
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
## Exception Assertions ##
Packit bd1cd8
Packit bd1cd8
These are for verifying that a piece of code throws (or does not
Packit bd1cd8
throw) an exception of the given type:
Packit bd1cd8
Packit bd1cd8
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
Packit bd1cd8
|:--------------------|:-----------------------|:-------------|
Packit bd1cd8
| `ASSERT_THROW(`_statement_, _exception\_type_`);`  | `EXPECT_THROW(`_statement_, _exception\_type_`);`  | _statement_ throws an exception of the given type  |
Packit bd1cd8
| `ASSERT_ANY_THROW(`_statement_`);`                | `EXPECT_ANY_THROW(`_statement_`);`                | _statement_ throws an exception of any type        |
Packit bd1cd8
| `ASSERT_NO_THROW(`_statement_`);`                 | `EXPECT_NO_THROW(`_statement_`);`                 | _statement_ doesn't throw any exception            |
Packit bd1cd8
Packit bd1cd8
Examples:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
ASSERT_THROW(Foo(5), bar_exception);
Packit bd1cd8
Packit bd1cd8
EXPECT_NO_THROW({
Packit bd1cd8
  int n = 5;
Packit bd1cd8
  Bar(&n);
Packit bd1cd8
});
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac; since version 1.1.0.
Packit bd1cd8
Packit bd1cd8
## Predicate Assertions for Better Error Messages ##
Packit bd1cd8
Packit bd1cd8
Even though Google Test has a rich set of assertions, they can never be
Packit bd1cd8
complete, as it's impossible (nor a good idea) to anticipate all the scenarios
Packit bd1cd8
a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()`
Packit bd1cd8
to check a complex expression, for lack of a better macro. This has the problem
Packit bd1cd8
of not showing you the values of the parts of the expression, making it hard to
Packit bd1cd8
understand what went wrong. As a workaround, some users choose to construct the
Packit bd1cd8
failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
Packit bd1cd8
is awkward especially when the expression has side-effects or is expensive to
Packit bd1cd8
evaluate.
Packit bd1cd8
Packit bd1cd8
Google Test gives you three different options to solve this problem:
Packit bd1cd8
Packit bd1cd8
### Using an Existing Boolean Function ###
Packit bd1cd8
Packit bd1cd8
If you already have a function or a functor that returns `bool` (or a type
Packit bd1cd8
that can be implicitly converted to `bool`), you can use it in a _predicate
Packit bd1cd8
assertion_ to get the function arguments printed for free:
Packit bd1cd8
Packit bd1cd8
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
Packit bd1cd8
|:--------------------|:-----------------------|:-------------|
Packit bd1cd8
| `ASSERT_PRED1(`_pred1, val1_`);`       | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true |
Packit bd1cd8
| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` |  _pred2(val1, val2)_ returns true |
Packit bd1cd8
|  ...                | ...                    | ...          |
Packit bd1cd8
Packit bd1cd8
In the above, _predn_ is an _n_-ary predicate function or functor, where
Packit bd1cd8
_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds
Packit bd1cd8
if the predicate returns `true` when applied to the given arguments, and fails
Packit bd1cd8
otherwise. When the assertion fails, it prints the value of each argument. In
Packit bd1cd8
either case, the arguments are evaluated exactly once.
Packit bd1cd8
Packit bd1cd8
Here's an example. Given
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
// Returns true iff m and n have no common divisors except 1.
Packit bd1cd8
bool MutuallyPrime(int m, int n) { ... }
Packit bd1cd8
const int a = 3;
Packit bd1cd8
const int b = 4;
Packit bd1cd8
const int c = 10;
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the
Packit bd1cd8
assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
!MutuallyPrime(b, c) is false, where
Packit bd1cd8
b is 4
Packit bd1cd8
c is 10
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
**Notes:**
Packit bd1cd8
Packit bd1cd8
  1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this FAQ](FAQ.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert_predn-how-do-i-fix-it) for how to resolve it.
Packit bd1cd8
  1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know.
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac
Packit bd1cd8
Packit bd1cd8
### Using a Function That Returns an AssertionResult ###
Packit bd1cd8
Packit bd1cd8
While `EXPECT_PRED*()` and friends are handy for a quick job, the
Packit bd1cd8
syntax is not satisfactory: you have to use different macros for
Packit bd1cd8
different arities, and it feels more like Lisp than C++.  The
Packit bd1cd8
`::testing::AssertionResult` class solves this problem.
Packit bd1cd8
Packit bd1cd8
An `AssertionResult` object represents the result of an assertion
Packit bd1cd8
(whether it's a success or a failure, and an associated message).  You
Packit bd1cd8
can create an `AssertionResult` using one of these factory
Packit bd1cd8
functions:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
namespace testing {
Packit bd1cd8
Packit bd1cd8
// Returns an AssertionResult object to indicate that an assertion has
Packit bd1cd8
// succeeded.
Packit bd1cd8
AssertionResult AssertionSuccess();
Packit bd1cd8
Packit bd1cd8
// Returns an AssertionResult object to indicate that an assertion has
Packit bd1cd8
// failed.
Packit bd1cd8
AssertionResult AssertionFailure();
Packit bd1cd8
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
You can then use the `<<` operator to stream messages to the
Packit bd1cd8
`AssertionResult` object.
Packit bd1cd8
Packit bd1cd8
To provide more readable messages in Boolean assertions
Packit bd1cd8
(e.g. `EXPECT_TRUE()`), write a predicate function that returns
Packit bd1cd8
`AssertionResult` instead of `bool`. For example, if you define
Packit bd1cd8
`IsEven()` as:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
::testing::AssertionResult IsEven(int n) {
Packit bd1cd8
  if ((n % 2) == 0)
Packit bd1cd8
    return ::testing::AssertionSuccess();
Packit bd1cd8
  else
Packit bd1cd8
    return ::testing::AssertionFailure() << n << " is odd";
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
instead of:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
bool IsEven(int n) {
Packit bd1cd8
  return (n % 2) == 0;
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print:
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
Value of: IsEven(Fib(4))
Packit bd1cd8
Actual: false (*3 is odd*)
Packit bd1cd8
Expected: true
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
instead of a more opaque
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
Value of: IsEven(Fib(4))
Packit bd1cd8
Actual: false
Packit bd1cd8
Expected: true
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE`
Packit bd1cd8
as well, and are fine with making the predicate slower in the success
Packit bd1cd8
case, you can supply a success message:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
::testing::AssertionResult IsEven(int n) {
Packit bd1cd8
  if ((n % 2) == 0)
Packit bd1cd8
    return ::testing::AssertionSuccess() << n << " is even";
Packit bd1cd8
  else
Packit bd1cd8
    return ::testing::AssertionFailure() << n << " is odd";
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
Value of: IsEven(Fib(6))
Packit bd1cd8
Actual: true (8 is even)
Packit bd1cd8
Expected: false
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac; since version 1.4.1.
Packit bd1cd8
Packit bd1cd8
### Using a Predicate-Formatter ###
Packit bd1cd8
Packit bd1cd8
If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and
Packit bd1cd8
`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your
Packit bd1cd8
predicate do not support streaming to `ostream`, you can instead use the
Packit bd1cd8
following _predicate-formatter assertions_ to _fully_ customize how the
Packit bd1cd8
message is formatted:
Packit bd1cd8
Packit bd1cd8
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
Packit bd1cd8
|:--------------------|:-----------------------|:-------------|
Packit bd1cd8
| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);`        | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`);` | _pred\_format1(val1)_ is successful |
Packit bd1cd8
| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful |
Packit bd1cd8
| `...`               | `...`                  | `...`        |
Packit bd1cd8
Packit bd1cd8
The difference between this and the previous two groups of macros is that instead of
Packit bd1cd8
a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_
Packit bd1cd8
(_pred\_formatn_), which is a function or functor with the signature:
Packit bd1cd8
Packit bd1cd8
`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);`
Packit bd1cd8
Packit bd1cd8
where _val1_, _val2_, ..., and _valn_ are the values of the predicate
Packit bd1cd8
arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding
Packit bd1cd8
expressions as they appear in the source code. The types `T1`, `T2`, ..., and
Packit bd1cd8
`Tn` can be either value types or reference types. For example, if an
Packit bd1cd8
argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`,
Packit bd1cd8
whichever is appropriate.
Packit bd1cd8
Packit bd1cd8
A predicate-formatter returns a `::testing::AssertionResult` object to indicate
Packit bd1cd8
whether the assertion has succeeded or not. The only way to create such an
Packit bd1cd8
object is to call one of these factory functions:
Packit bd1cd8
Packit bd1cd8
As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
// Returns the smallest prime common divisor of m and n,
Packit bd1cd8
// or 1 when m and n are mutually prime.
Packit bd1cd8
int SmallestPrimeCommonDivisor(int m, int n) { ... }
Packit bd1cd8
Packit bd1cd8
// A predicate-formatter for asserting that two integers are mutually prime.
Packit bd1cd8
::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
Packit bd1cd8
                                               const char* n_expr,
Packit bd1cd8
                                               int m,
Packit bd1cd8
                                               int n) {
Packit bd1cd8
  if (MutuallyPrime(m, n))
Packit bd1cd8
    return ::testing::AssertionSuccess();
Packit bd1cd8
Packit bd1cd8
  return ::testing::AssertionFailure()
Packit bd1cd8
      << m_expr << " and " << n_expr << " (" << m << " and " << n
Packit bd1cd8
      << ") are not mutually prime, " << "as they have a common divisor "
Packit bd1cd8
      << SmallestPrimeCommonDivisor(m, n);
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
With this predicate-formatter, we can use
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
to generate the message
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
b and c (4 and 10) are not mutually prime, as they have a common divisor 2.
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
As you may have realized, many of the assertions we introduced earlier are
Packit bd1cd8
special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are
Packit bd1cd8
indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`.
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
## Floating-Point Comparison ##
Packit bd1cd8
Packit bd1cd8
Comparing floating-point numbers is tricky. Due to round-off errors, it is
Packit bd1cd8
very unlikely that two floating-points will match exactly. Therefore,
Packit bd1cd8
`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points
Packit bd1cd8
can have a wide value range, no single fixed error bound works. It's better to
Packit bd1cd8
compare by a fixed relative error bound, except for values close to 0 due to
Packit bd1cd8
the loss of precision there.
Packit bd1cd8
Packit bd1cd8
In general, for floating-point comparison to make sense, the user needs to
Packit bd1cd8
carefully choose the error bound. If they don't want or care to, comparing in
Packit bd1cd8
terms of Units in the Last Place (ULPs) is a good default, and Google Test
Packit bd1cd8
provides assertions to do this. Full details about ULPs are quite long; if you
Packit bd1cd8
want to learn more, see
Packit bd1cd8
[this article on float comparison](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm).
Packit bd1cd8
Packit bd1cd8
### Floating-Point Macros ###
Packit bd1cd8
Packit bd1cd8
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
Packit bd1cd8
|:--------------------|:-----------------------|:-------------|
Packit bd1cd8
| `ASSERT_FLOAT_EQ(`_val1, val2_`);`  | `EXPECT_FLOAT_EQ(`_val1, val2_`);` | the two `float` values are almost equal |
Packit bd1cd8
| `ASSERT_DOUBLE_EQ(`_val1, val2_`);` | `EXPECT_DOUBLE_EQ(`_val1, val2_`);` | the two `double` values are almost equal |
Packit bd1cd8
Packit bd1cd8
By "almost equal", we mean the two values are within 4 ULP's from each
Packit bd1cd8
other.
Packit bd1cd8
Packit bd1cd8
The following assertions allow you to choose the acceptable error bound:
Packit bd1cd8
Packit bd1cd8
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
Packit bd1cd8
|:--------------------|:-----------------------|:-------------|
Packit bd1cd8
| `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 |
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
### Floating-Point Predicate-Format Functions ###
Packit bd1cd8
Packit bd1cd8
Some floating-point operations are useful, but not that often used. In order
Packit bd1cd8
to avoid an explosion of new macros, we provide them as predicate-format
Packit bd1cd8
functions that can be used in predicate assertion macros (e.g.
Packit bd1cd8
`EXPECT_PRED_FORMAT2`, etc).
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2);
Packit bd1cd8
EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Verifies that _val1_ is less than, or almost equal to, _val2_. You can
Packit bd1cd8
replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`.
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
## Windows HRESULT assertions ##
Packit bd1cd8
Packit bd1cd8
These assertions test for `HRESULT` success or failure.
Packit bd1cd8
Packit bd1cd8
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
Packit bd1cd8
|:--------------------|:-----------------------|:-------------|
Packit bd1cd8
| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` |
Packit bd1cd8
| `ASSERT_HRESULT_FAILED(`_expression_`);`    | `EXPECT_HRESULT_FAILED(`_expression_`);`    | _expression_ is a failure `HRESULT` |
Packit bd1cd8
Packit bd1cd8
The generated output contains the human-readable error message
Packit bd1cd8
associated with the `HRESULT` code returned by _expression_.
Packit bd1cd8
Packit bd1cd8
You might use them like this:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
CComPtr shell;
Packit bd1cd8
ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application"));
Packit bd1cd8
CComVariant empty;
Packit bd1cd8
ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
_Availability_: Windows.
Packit bd1cd8
Packit bd1cd8
## Type Assertions ##
Packit bd1cd8
Packit bd1cd8
You can call the function
Packit bd1cd8
```
Packit bd1cd8
::testing::StaticAssertTypeEq<T1, T2>();
Packit bd1cd8
```
Packit bd1cd8
to assert that types `T1` and `T2` are the same.  The function does
Packit bd1cd8
nothing if the assertion is satisfied.  If the types are different,
Packit bd1cd8
the function call will fail to compile, and the compiler error message
Packit bd1cd8
will likely (depending on the compiler) show you the actual values of
Packit bd1cd8
`T1` and `T2`.  This is mainly useful inside template code.
Packit bd1cd8
Packit bd1cd8
_Caveat:_ When used inside a member function of a class template or a
Packit bd1cd8
function template, `StaticAssertTypeEq<T1, T2>()` is effective _only if_
Packit bd1cd8
the function is instantiated.  For example, given:
Packit bd1cd8
```
Packit bd1cd8
template <typename T> class Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  void Bar() { ::testing::StaticAssertTypeEq<int, T>(); }
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
the code:
Packit bd1cd8
```
Packit bd1cd8
void Test1() { Foo<bool> foo; }
Packit bd1cd8
```
Packit bd1cd8
will _not_ generate a compiler error, as `Foo<bool>::Bar()` is never
Packit bd1cd8
actually instantiated.  Instead, you need:
Packit bd1cd8
```
Packit bd1cd8
void Test2() { Foo<bool> foo; foo.Bar(); }
Packit bd1cd8
```
Packit bd1cd8
to cause a compiler error.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac; since version 1.3.0.
Packit bd1cd8
Packit bd1cd8
## Assertion Placement ##
Packit bd1cd8
Packit bd1cd8
You can use assertions in any C++ function. In particular, it doesn't
Packit bd1cd8
have to be a method of the test fixture class. The one constraint is
Packit bd1cd8
that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`)
Packit bd1cd8
can only be used in void-returning functions. This is a consequence of
Packit bd1cd8
Google Test not using exceptions. By placing it in a non-void function
Packit bd1cd8
you'll get a confusing compile error like
Packit bd1cd8
`"error: void value not ignored as it ought to be"`.
Packit bd1cd8
Packit bd1cd8
If you need to use assertions in a function that returns non-void, one option
Packit bd1cd8
is to make the function return the value in an out parameter instead. For
Packit bd1cd8
example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You
Packit bd1cd8
need to make sure that `*result` contains some sensible value even when the
Packit bd1cd8
function returns prematurely. As the function now returns `void`, you can use
Packit bd1cd8
any assertion inside of it.
Packit bd1cd8
Packit bd1cd8
If changing the function's type is not an option, you should just use
Packit bd1cd8
assertions that generate non-fatal failures, such as `ADD_FAILURE*` and
Packit bd1cd8
`EXPECT_*`.
Packit bd1cd8
Packit bd1cd8
_Note_: Constructors and destructors are not considered void-returning
Packit bd1cd8
functions, according to the C++ language specification, and so you may not use
Packit bd1cd8
fatal assertions in them. You'll get a compilation error if you try. A simple
Packit bd1cd8
workaround is to transfer the entire body of the constructor or destructor to a
Packit bd1cd8
private void-returning method. However, you should be aware that a fatal
Packit bd1cd8
assertion failure in a constructor does not terminate the current test, as your
Packit bd1cd8
intuition might suggest; it merely returns from the constructor early, possibly
Packit bd1cd8
leaving your object in a partially-constructed state. Likewise, a fatal
Packit bd1cd8
assertion failure in a destructor may leave your object in a
Packit bd1cd8
partially-destructed state. Use assertions carefully in these situations!
Packit bd1cd8
Packit bd1cd8
# Teaching Google Test How to Print Your Values #
Packit bd1cd8
Packit bd1cd8
When a test assertion such as `EXPECT_EQ` fails, Google Test prints the
Packit bd1cd8
argument values to help you debug.  It does this using a
Packit bd1cd8
user-extensible value printer.
Packit bd1cd8
Packit bd1cd8
This printer knows how to print built-in C++ types, native arrays, STL
Packit bd1cd8
containers, and any type that supports the `<<` operator.  For other
Packit bd1cd8
types, it prints the raw bytes in the value and hopes that you the
Packit bd1cd8
user can figure it out.
Packit bd1cd8
Packit bd1cd8
As mentioned earlier, the printer is _extensible_.  That means
Packit bd1cd8
you can teach it to do a better job at printing your particular type
Packit bd1cd8
than to dump the bytes.  To do that, define `<<` for your type:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
#include <iostream>
Packit bd1cd8
Packit bd1cd8
namespace foo {
Packit bd1cd8
Packit bd1cd8
class Bar { ... };  // We want Google Test to be able to print instances of this.
Packit bd1cd8
Packit bd1cd8
// It's important that the << operator is defined in the SAME
Packit bd1cd8
// namespace that defines Bar.  C++'s look-up rules rely on that.
Packit bd1cd8
::std::ostream& operator<<(::std::ostream& os, const Bar& bar) {
Packit bd1cd8
  return os << bar.DebugString();  // whatever needed to print bar to os
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
}  // namespace foo
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Sometimes, this might not be an option: your team may consider it bad
Packit bd1cd8
style to have a `<<` operator for `Bar`, or `Bar` may already have a
Packit bd1cd8
`<<` operator that doesn't do what you want (and you cannot change
Packit bd1cd8
it).  If so, you can instead define a `PrintTo()` function like this:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
#include <iostream>
Packit bd1cd8
Packit bd1cd8
namespace foo {
Packit bd1cd8
Packit bd1cd8
class Bar { ... };
Packit bd1cd8
Packit bd1cd8
// It's important that PrintTo() is defined in the SAME
Packit bd1cd8
// namespace that defines Bar.  C++'s look-up rules rely on that.
Packit bd1cd8
void PrintTo(const Bar& bar, ::std::ostream* os) {
Packit bd1cd8
  *os << bar.DebugString();  // whatever needed to print bar to os
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
}  // namespace foo
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
If you have defined both `<<` and `PrintTo()`, the latter will be used
Packit bd1cd8
when Google Test is concerned.  This allows you to customize how the value
Packit bd1cd8
appears in Google Test's output without affecting code that relies on the
Packit bd1cd8
behavior of its `<<` operator.
Packit bd1cd8
Packit bd1cd8
If you want to print a value `x` using Google Test's value printer
Packit bd1cd8
yourself, just call `::testing::PrintToString(`_x_`)`, which
Packit bd1cd8
returns an `std::string`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
vector<pair<Bar, int> > bar_ints = GetBarIntVector();
Packit bd1cd8
Packit bd1cd8
EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
Packit bd1cd8
    << "bar_ints = " << ::testing::PrintToString(bar_ints);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
# Death Tests #
Packit bd1cd8
Packit bd1cd8
In many applications, there are assertions that can cause application failure
Packit bd1cd8
if a condition is not met. These sanity checks, which ensure that the program
Packit bd1cd8
is in a known good state, are there to fail at the earliest possible time after
Packit bd1cd8
some program state is corrupted. If the assertion checks the wrong condition,
Packit bd1cd8
then the program may proceed in an erroneous state, which could lead to memory
Packit bd1cd8
corruption, security holes, or worse. Hence it is vitally important to test
Packit bd1cd8
that such assertion statements work as expected.
Packit bd1cd8
Packit bd1cd8
Since these precondition checks cause the processes to die, we call such tests
Packit bd1cd8
_death tests_. More generally, any test that checks that a program terminates
Packit bd1cd8
(except by throwing an exception) in an expected fashion is also a death test.
Packit bd1cd8
Packit bd1cd8
Note that if a piece of code throws an exception, we don't consider it "death"
Packit bd1cd8
for the purpose of death tests, as the caller of the code could catch the exception
Packit bd1cd8
and avoid the crash. If you want to verify exceptions thrown by your code,
Packit bd1cd8
see [Exception Assertions](#exception-assertions).
Packit bd1cd8
Packit bd1cd8
If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#catching-failures).
Packit bd1cd8
Packit bd1cd8
## How to Write a Death Test ##
Packit bd1cd8
Packit bd1cd8
Google Test has the following macros to support death tests:
Packit bd1cd8
Packit bd1cd8
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
Packit bd1cd8
|:--------------------|:-----------------------|:-------------|
Packit bd1cd8
| `ASSERT_DEATH(`_statement, regex_`);` | `EXPECT_DEATH(`_statement, regex_`);` | _statement_ crashes with the given error |
Packit bd1cd8
| `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 |
Packit bd1cd8
| `ASSERT_EXIT(`_statement, predicate, regex_`);` | `EXPECT_EXIT(`_statement, predicate, regex_`);` |_statement_ exits with the given error and its exit code matches _predicate_ |
Packit bd1cd8
Packit bd1cd8
where _statement_ is a statement that is expected to cause the process to
Packit bd1cd8
die, _predicate_ is a function or function object that evaluates an integer
Packit bd1cd8
exit status, and _regex_ is a regular expression that the stderr output of
Packit bd1cd8
_statement_ is expected to match. Note that _statement_ can be _any valid
Packit bd1cd8
statement_ (including _compound statement_) and doesn't have to be an
Packit bd1cd8
expression.
Packit bd1cd8
Packit bd1cd8
As usual, the `ASSERT` variants abort the current test function, while the
Packit bd1cd8
`EXPECT` variants do not.
Packit bd1cd8
Packit bd1cd8
**Note:** We use the word "crash" here to mean that the process
Packit bd1cd8
terminates with a _non-zero_ exit status code.  There are two
Packit bd1cd8
possibilities: either the process has called `exit()` or `_exit()`
Packit bd1cd8
with a non-zero value, or it may be killed by a signal.
Packit bd1cd8
Packit bd1cd8
This means that if _statement_ terminates the process with a 0 exit
Packit bd1cd8
code, it is _not_ considered a crash by `EXPECT_DEATH`.  Use
Packit bd1cd8
`EXPECT_EXIT` instead if this is the case, or if you want to restrict
Packit bd1cd8
the exit code more precisely.
Packit bd1cd8
Packit bd1cd8
A predicate here must accept an `int` and return a `bool`. The death test
Packit bd1cd8
succeeds only if the predicate returns `true`. Google Test defines a few
Packit bd1cd8
predicates that handle the most common cases:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
::testing::ExitedWithCode(exit_code)
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
This expression is `true` if the program exited normally with the given exit
Packit bd1cd8
code.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
::testing::KilledBySignal(signal_number)  // Not available on Windows.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
This expression is `true` if the program was killed by the given signal.
Packit bd1cd8
Packit bd1cd8
The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate
Packit bd1cd8
that verifies the process' exit code is non-zero.
Packit bd1cd8
Packit bd1cd8
Note that a death test only cares about three things:
Packit bd1cd8
Packit bd1cd8
  1. does _statement_ abort or exit the process?
Packit bd1cd8
  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
Packit bd1cd8
  1. does the stderr output match _regex_?
Packit bd1cd8
Packit bd1cd8
In 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.
Packit bd1cd8
Packit bd1cd8
To write a death test, simply use one of the above macros inside your test
Packit bd1cd8
function. For example,
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TEST(MyDeathTest, Foo) {
Packit bd1cd8
  // This death test uses a compound statement.
Packit bd1cd8
  ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()");
Packit bd1cd8
}
Packit bd1cd8
TEST(MyDeathTest, NormalExit) {
Packit bd1cd8
  EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success");
Packit bd1cd8
}
Packit bd1cd8
TEST(MyDeathTest, KillMyself) {
Packit bd1cd8
  EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal");
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
verifies that:
Packit bd1cd8
Packit bd1cd8
  * calling `Foo(5)` causes the process to die with the given error message,
Packit bd1cd8
  * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and
Packit bd1cd8
  * calling `KillMyself()` kills the process with signal `SIGKILL`.
Packit bd1cd8
Packit bd1cd8
The test function body may contain other assertions and statements as well, if
Packit bd1cd8
necessary.
Packit bd1cd8
Packit bd1cd8
_Important:_ We strongly recommend you to follow the convention of naming your
Packit bd1cd8
test case (not test) `*DeathTest` when it contains a death test, as
Packit bd1cd8
demonstrated in the above example. The `Death Tests And Threads` section below
Packit bd1cd8
explains why.
Packit bd1cd8
Packit bd1cd8
If a test fixture class is shared by normal tests and death tests, you
Packit bd1cd8
can use typedef to introduce an alias for the fixture class and avoid
Packit bd1cd8
duplicating its code:
Packit bd1cd8
```
Packit bd1cd8
class FooTest : public ::testing::Test { ... };
Packit bd1cd8
Packit bd1cd8
typedef FooTest FooDeathTest;
Packit bd1cd8
Packit bd1cd8
TEST_F(FooTest, DoesThis) {
Packit bd1cd8
  // normal test
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
TEST_F(FooDeathTest, DoesThat) {
Packit bd1cd8
  // death test
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
_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.
Packit bd1cd8
Packit bd1cd8
## Regular Expression Syntax ##
Packit bd1cd8
Packit bd1cd8
On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the
Packit bd1cd8
[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
Packit bd1cd8
syntax 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).
Packit bd1cd8
Packit bd1cd8
On Windows, Google Test uses its own simple regular expression
Packit bd1cd8
implementation. It lacks many features you can find in POSIX extended
Packit bd1cd8
regular expressions.  For example, we don't support union (`"x|y"`),
Packit bd1cd8
grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count
Packit bd1cd8
(`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a
Packit bd1cd8
literal character, period (`.`), or a single `\\` escape sequence; `x`
Packit bd1cd8
and `y` denote regular expressions.):
Packit bd1cd8
Packit bd1cd8
| `c` | matches any literal character `c` |
Packit bd1cd8
|:----|:----------------------------------|
Packit bd1cd8
| `\\d` | matches any decimal digit         |
Packit bd1cd8
| `\\D` | matches any character that's not a decimal digit |
Packit bd1cd8
| `\\f` | matches `\f`                      |
Packit bd1cd8
| `\\n` | matches `\n`                      |
Packit bd1cd8
| `\\r` | matches `\r`                      |
Packit bd1cd8
| `\\s` | matches any ASCII whitespace, including `\n` |
Packit bd1cd8
| `\\S` | matches any character that's not a whitespace |
Packit bd1cd8
| `\\t` | matches `\t`                      |
Packit bd1cd8
| `\\v` | matches `\v`                      |
Packit bd1cd8
| `\\w` | matches any letter, `_`, or decimal digit |
Packit bd1cd8
| `\\W` | matches any character that `\\w` doesn't match |
Packit bd1cd8
| `\\c` | matches any literal character `c`, which must be a punctuation |
Packit bd1cd8
| `\\.` | matches the `.` character         |
Packit bd1cd8
| `.` | matches any single character except `\n` |
Packit bd1cd8
| `A?` | matches 0 or 1 occurrences of `A` |
Packit bd1cd8
| `A*` | matches 0 or many occurrences of `A` |
Packit bd1cd8
| `A+` | matches 1 or many occurrences of `A` |
Packit bd1cd8
| `^` | matches the beginning of a string (not that of each line) |
Packit bd1cd8
| `$` | matches the end of a string (not that of each line) |
Packit bd1cd8
| `xy` | matches `x` followed by `y`       |
Packit bd1cd8
Packit bd1cd8
To help you determine which capability is available on your system,
Packit bd1cd8
Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX
Packit bd1cd8
extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses
Packit bd1cd8
the simple version.  If you want your death tests to work in both
Packit bd1cd8
cases, you can either `#if` on these macros or use the more limited
Packit bd1cd8
syntax only.
Packit bd1cd8
Packit bd1cd8
## How It Works ##
Packit bd1cd8
Packit bd1cd8
Under the hood, `ASSERT_EXIT()` spawns a new process and executes the
Packit bd1cd8
death test statement in that process. The details of of how precisely
Packit bd1cd8
that happens depend on the platform and the variable
Packit bd1cd8
`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the
Packit bd1cd8
command-line flag `--gtest_death_test_style`).
Packit bd1cd8
Packit bd1cd8
  * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which:
Packit bd1cd8
    * If the variable's value is `"fast"`, the death test statement is immediately executed.
Packit bd1cd8
    * 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.
Packit bd1cd8
  * 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.
Packit bd1cd8
Packit bd1cd8
Other values for the variable are illegal and will cause the death test to
Packit bd1cd8
fail. Currently, the flag's default value is `"fast"`. However, we reserve the
Packit bd1cd8
right to change it in the future. Therefore, your tests should not depend on
Packit bd1cd8
this.
Packit bd1cd8
Packit bd1cd8
In either case, the parent process waits for the child process to complete, and checks that
Packit bd1cd8
Packit bd1cd8
  1. the child's exit status satisfies the predicate, and
Packit bd1cd8
  1. the child's stderr matches the regular expression.
Packit bd1cd8
Packit bd1cd8
If the death test statement runs to completion without dying, the child
Packit bd1cd8
process will nonetheless terminate, and the assertion fails.
Packit bd1cd8
Packit bd1cd8
## Death Tests And Threads ##
Packit bd1cd8
Packit bd1cd8
The reason for the two death test styles has to do with thread safety. Due to
Packit bd1cd8
well-known problems with forking in the presence of threads, death tests should
Packit bd1cd8
be run in a single-threaded context. Sometimes, however, it isn't feasible to
Packit bd1cd8
arrange that kind of environment. For example, statically-initialized modules
Packit bd1cd8
may start threads before main is ever reached. Once threads have been created,
Packit bd1cd8
it may be difficult or impossible to clean them up.
Packit bd1cd8
Packit bd1cd8
Google Test has three features intended to raise awareness of threading issues.
Packit bd1cd8
Packit bd1cd8
  1. A warning is emitted if multiple threads are running when a death test is encountered.
Packit bd1cd8
  1. Test cases with a name ending in "DeathTest" are run before all other tests.
Packit bd1cd8
  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.
Packit bd1cd8
Packit bd1cd8
It's perfectly fine to create threads inside a death test statement; they are
Packit bd1cd8
executed in a separate process and cannot affect the parent.
Packit bd1cd8
Packit bd1cd8
## Death Test Styles ##
Packit bd1cd8
Packit bd1cd8
The "threadsafe" death test style was introduced in order to help mitigate the
Packit bd1cd8
risks of testing in a possibly multithreaded environment. It trades increased
Packit bd1cd8
test execution time (potentially dramatically so) for improved thread safety.
Packit bd1cd8
We suggest using the faster, default "fast" style unless your test has specific
Packit bd1cd8
problems with it.
Packit bd1cd8
Packit bd1cd8
You can choose a particular style of death tests by setting the flag
Packit bd1cd8
programmatically:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
::testing::FLAGS_gtest_death_test_style = "threadsafe";
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
You can do this in `main()` to set the style for all death tests in the
Packit bd1cd8
binary, or in individual tests. Recall that flags are saved before running each
Packit bd1cd8
test and restored afterwards, so you need not do that yourself. For example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TEST(MyDeathTest, TestOne) {
Packit bd1cd8
  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
Packit bd1cd8
  // This test is run in the "threadsafe" style:
Packit bd1cd8
  ASSERT_DEATH(ThisShouldDie(), "");
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
TEST(MyDeathTest, TestTwo) {
Packit bd1cd8
  // This test is run in the "fast" style:
Packit bd1cd8
  ASSERT_DEATH(ThisShouldDie(), "");
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
int main(int argc, char** argv) {
Packit bd1cd8
  ::testing::InitGoogleTest(&argc, argv);
Packit bd1cd8
  ::testing::FLAGS_gtest_death_test_style = "fast";
Packit bd1cd8
  return RUN_ALL_TESTS();
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Caveats ##
Packit bd1cd8
Packit bd1cd8
The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement.
Packit bd1cd8
If it leaves the current function via a `return` statement or by throwing an exception,
Packit bd1cd8
the death test is considered to have failed.  Some Google Test macros may return
Packit bd1cd8
from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_.
Packit bd1cd8
Packit bd1cd8
Since _statement_ runs in the child process, any in-memory side effect (e.g.
Packit bd1cd8
modifying a variable, releasing memory, etc) it causes will _not_ be observable
Packit bd1cd8
in the parent process. In particular, if you release memory in a death test,
Packit bd1cd8
your program will fail the heap check as the parent process will never see the
Packit bd1cd8
memory reclaimed. To solve this problem, you can
Packit bd1cd8
Packit bd1cd8
  1. try not to free memory in a death test;
Packit bd1cd8
  1. free the memory again in the parent process; or
Packit bd1cd8
  1. do not use the heap checker in your program.
Packit bd1cd8
Packit bd1cd8
Due to an implementation detail, you cannot place multiple death test
Packit bd1cd8
assertions on the same line; otherwise, compilation will fail with an unobvious
Packit bd1cd8
error message.
Packit bd1cd8
Packit bd1cd8
Despite the improved thread safety afforded by the "threadsafe" style of death
Packit bd1cd8
test, thread problems such as deadlock are still possible in the presence of
Packit bd1cd8
handlers registered with `pthread_atfork(3)`.
Packit bd1cd8
Packit bd1cd8
# Using Assertions in Sub-routines #
Packit bd1cd8
Packit bd1cd8
## Adding Traces to Assertions ##
Packit bd1cd8
Packit bd1cd8
If a test sub-routine is called from several places, when an assertion
Packit bd1cd8
inside it fails, it can be hard to tell which invocation of the
Packit bd1cd8
sub-routine the failure is from.  You can alleviate this problem using
Packit bd1cd8
extra logging or custom failure messages, but that usually clutters up
Packit bd1cd8
your tests. A better solution is to use the `SCOPED_TRACE` macro:
Packit bd1cd8
Packit bd1cd8
| `SCOPED_TRACE(`_message_`);` |
Packit bd1cd8
|:-----------------------------|
Packit bd1cd8
Packit bd1cd8
where _message_ can be anything streamable to `std::ostream`. This
Packit bd1cd8
macro will cause the current file name, line number, and the given
Packit bd1cd8
message to be added in every failure message. The effect will be
Packit bd1cd8
undone when the control leaves the current lexical scope.
Packit bd1cd8
Packit bd1cd8
For example,
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
10: void Sub1(int n) {
Packit bd1cd8
11:   EXPECT_EQ(1, Bar(n));
Packit bd1cd8
12:   EXPECT_EQ(2, Bar(n + 1));
Packit bd1cd8
13: }
Packit bd1cd8
14:
Packit bd1cd8
15: TEST(FooTest, Bar) {
Packit bd1cd8
16:   {
Packit bd1cd8
17:     SCOPED_TRACE("A");  // This trace point will be included in
Packit bd1cd8
18:                         // every failure in this scope.
Packit bd1cd8
19:     Sub1(1);
Packit bd1cd8
20:   }
Packit bd1cd8
21:   // Now it won't.
Packit bd1cd8
22:   Sub1(9);
Packit bd1cd8
23: }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
could result in messages like these:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
path/to/foo_test.cc:11: Failure
Packit bd1cd8
Value of: Bar(n)
Packit bd1cd8
Expected: 1
Packit bd1cd8
  Actual: 2
Packit bd1cd8
   Trace:
Packit bd1cd8
path/to/foo_test.cc:17: A
Packit bd1cd8
Packit bd1cd8
path/to/foo_test.cc:12: Failure
Packit bd1cd8
Value of: Bar(n + 1)
Packit bd1cd8
Expected: 2
Packit bd1cd8
  Actual: 3
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Without the trace, it would've been difficult to know which invocation
Packit bd1cd8
of `Sub1()` the two failures come from respectively. (You could add an
Packit bd1cd8
extra message to each assertion in `Sub1()` to indicate the value of
Packit bd1cd8
`n`, but that's tedious.)
Packit bd1cd8
Packit bd1cd8
Some tips on using `SCOPED_TRACE`:
Packit bd1cd8
Packit bd1cd8
  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.
Packit bd1cd8
  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.
Packit bd1cd8
  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 `""`.
Packit bd1cd8
  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.
Packit bd1cd8
  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!
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
## Propagating Fatal Failures ##
Packit bd1cd8
Packit bd1cd8
A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that
Packit bd1cd8
when they fail they only abort the _current function_, not the entire test. For
Packit bd1cd8
example, the following test will segfault:
Packit bd1cd8
```
Packit bd1cd8
void Subroutine() {
Packit bd1cd8
  // Generates a fatal failure and aborts the current function.
Packit bd1cd8
  ASSERT_EQ(1, 2);
Packit bd1cd8
  // The following won't be executed.
Packit bd1cd8
  ...
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
TEST(FooTest, Bar) {
Packit bd1cd8
  Subroutine();
Packit bd1cd8
  // The intended behavior is for the fatal failure
Packit bd1cd8
  // in Subroutine() to abort the entire test.
Packit bd1cd8
  // The actual behavior: the function goes on after Subroutine() returns.
Packit bd1cd8
  int* p = NULL;
Packit bd1cd8
  *p = 3; // Segfault!
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Since we don't use exceptions, it is technically impossible to
Packit bd1cd8
implement the intended behavior here.  To alleviate this, Google Test
Packit bd1cd8
provides two solutions.  You could use either the
Packit bd1cd8
`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
Packit bd1cd8
`HasFatalFailure()` function.  They are described in the following two
Packit bd1cd8
subsections.
Packit bd1cd8
Packit bd1cd8
### Asserting on Subroutines ###
Packit bd1cd8
Packit bd1cd8
As shown above, if your test calls a subroutine that has an `ASSERT_*`
Packit bd1cd8
failure in it, the test will continue after the subroutine
Packit bd1cd8
returns. This may not be what you want.
Packit bd1cd8
Packit bd1cd8
Often people want fatal failures to propagate like exceptions.  For
Packit bd1cd8
that Google Test offers the following macros:
Packit bd1cd8
Packit bd1cd8
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
Packit bd1cd8
|:--------------------|:-----------------------|:-------------|
Packit bd1cd8
| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. |
Packit bd1cd8
Packit bd1cd8
Only failures in the thread that executes the assertion are checked to
Packit bd1cd8
determine the result of this type of assertions.  If _statement_
Packit bd1cd8
creates new threads, failures in these threads are ignored.
Packit bd1cd8
Packit bd1cd8
Examples:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
ASSERT_NO_FATAL_FAILURE(Foo());
Packit bd1cd8
Packit bd1cd8
int i;
Packit bd1cd8
EXPECT_NO_FATAL_FAILURE({
Packit bd1cd8
  i = Bar();
Packit bd1cd8
});
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac. Assertions from multiple threads
Packit bd1cd8
are currently not supported.
Packit bd1cd8
Packit bd1cd8
### Checking for Failures in the Current Test ###
Packit bd1cd8
Packit bd1cd8
`HasFatalFailure()` in the `::testing::Test` class returns `true` if an
Packit bd1cd8
assertion in the current test has suffered a fatal failure. This
Packit bd1cd8
allows functions to catch fatal failures in a sub-routine and return
Packit bd1cd8
early.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class Test {
Packit bd1cd8
 public:
Packit bd1cd8
  ...
Packit bd1cd8
  static bool HasFatalFailure();
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The typical usage, which basically simulates the behavior of a thrown
Packit bd1cd8
exception, is:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TEST(FooTest, Bar) {
Packit bd1cd8
  Subroutine();
Packit bd1cd8
  // Aborts if Subroutine() had a fatal failure.
Packit bd1cd8
  if (HasFatalFailure())
Packit bd1cd8
    return;
Packit bd1cd8
  // The following won't be executed.
Packit bd1cd8
  ...
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test
Packit bd1cd8
fixture, you must add the `::testing::Test::` prefix, as in:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
if (::testing::Test::HasFatalFailure())
Packit bd1cd8
  return;
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Similarly, `HasNonfatalFailure()` returns `true` if the current test
Packit bd1cd8
has at least one non-fatal failure, and `HasFailure()` returns `true`
Packit bd1cd8
if the current test has at least one failure of either kind.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.  `HasNonfatalFailure()` and
Packit bd1cd8
`HasFailure()` are available since version 1.4.0.
Packit bd1cd8
Packit bd1cd8
# Logging Additional Information #
Packit bd1cd8
Packit bd1cd8
In your test code, you can call `RecordProperty("key", value)` to log
Packit bd1cd8
additional 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
Packit bd1cd8
if you specify one. For example, the test
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TEST_F(WidgetUsageTest, MinAndMaxWidgets) {
Packit bd1cd8
  RecordProperty("MaximumWidgets", ComputeMaxUsage());
Packit bd1cd8
  RecordProperty("MinimumWidgets", ComputeMinUsage());
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
will output XML like this:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
...
Packit bd1cd8
  
Packit bd1cd8
            MaximumWidgets="12"
Packit bd1cd8
            MinimumWidgets="9" />
Packit bd1cd8
...
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
_Note_:
Packit bd1cd8
  * `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.
Packit bd1cd8
  * `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`).
Packit bd1cd8
  * 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.
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
# Sharing Resources Between Tests in the Same Test Case #
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
Google Test creates a new test fixture object for each test in order to make
Packit bd1cd8
tests independent and easier to debug. However, sometimes tests use resources
Packit bd1cd8
that are expensive to set up, making the one-copy-per-test model prohibitively
Packit bd1cd8
expensive.
Packit bd1cd8
Packit bd1cd8
If the tests don't change the resource, there's no harm in them sharing a
Packit bd1cd8
single resource copy. So, in addition to per-test set-up/tear-down, Google Test
Packit bd1cd8
also supports per-test-case set-up/tear-down. To use it:
Packit bd1cd8
Packit bd1cd8
  1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources.
Packit bd1cd8
  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.
Packit bd1cd8
Packit bd1cd8
That's it! Google Test automatically calls `SetUpTestCase()` before running the
Packit bd1cd8
_first test_ in the `FooTest` test case (i.e. before creating the first
Packit bd1cd8
`FooTest` object), and calls `TearDownTestCase()` after running the _last test_
Packit bd1cd8
in it (i.e. after deleting the last `FooTest` object). In between, the tests
Packit bd1cd8
can use the shared resources.
Packit bd1cd8
Packit bd1cd8
Remember that the test order is undefined, so your code can't depend on a test
Packit bd1cd8
preceding or following another. Also, the tests must either not modify the
Packit bd1cd8
state of any shared resource, or, if they do modify the state, they must
Packit bd1cd8
restore the state to its original value before passing control to the next
Packit bd1cd8
test.
Packit bd1cd8
Packit bd1cd8
Here's an example of per-test-case set-up and tear-down:
Packit bd1cd8
```
Packit bd1cd8
class FooTest : public ::testing::Test {
Packit bd1cd8
 protected:
Packit bd1cd8
  // Per-test-case set-up.
Packit bd1cd8
  // Called before the first test in this test case.
Packit bd1cd8
  // Can be omitted if not needed.
Packit bd1cd8
  static void SetUpTestCase() {
Packit bd1cd8
    shared_resource_ = new ...;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // Per-test-case tear-down.
Packit bd1cd8
  // Called after the last test in this test case.
Packit bd1cd8
  // Can be omitted if not needed.
Packit bd1cd8
  static void TearDownTestCase() {
Packit bd1cd8
    delete shared_resource_;
Packit bd1cd8
    shared_resource_ = NULL;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // You can define per-test set-up and tear-down logic as usual.
Packit bd1cd8
  virtual void SetUp() { ... }
Packit bd1cd8
  virtual void TearDown() { ... }
Packit bd1cd8
Packit bd1cd8
  // Some expensive resource shared by all tests.
Packit bd1cd8
  static T* shared_resource_;
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
T* FooTest::shared_resource_ = NULL;
Packit bd1cd8
Packit bd1cd8
TEST_F(FooTest, Test1) {
Packit bd1cd8
  ... you can refer to shared_resource here ...
Packit bd1cd8
}
Packit bd1cd8
TEST_F(FooTest, Test2) {
Packit bd1cd8
  ... you can refer to shared_resource here ...
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
# Global Set-Up and Tear-Down #
Packit bd1cd8
Packit bd1cd8
Just as you can do set-up and tear-down at the test level and the test case
Packit bd1cd8
level, you can also do it at the test program level. Here's how.
Packit bd1cd8
Packit bd1cd8
First, you subclass the `::testing::Environment` class to define a test
Packit bd1cd8
environment, which knows how to set-up and tear-down:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class Environment {
Packit bd1cd8
 public:
Packit bd1cd8
  virtual ~Environment() {}
Packit bd1cd8
  // Override this to define how to set up the environment.
Packit bd1cd8
  virtual void SetUp() {}
Packit bd1cd8
  // Override this to define how to tear down the environment.
Packit bd1cd8
  virtual void TearDown() {}
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Then, you register an instance of your environment class with Google Test by
Packit bd1cd8
calling the `::testing::AddGlobalTestEnvironment()` function:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
Environment* AddGlobalTestEnvironment(Environment* env);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of
Packit bd1cd8
the environment object, then runs the tests if there was no fatal failures, and
Packit bd1cd8
finally calls `TearDown()` of the environment object.
Packit bd1cd8
Packit bd1cd8
It's OK to register multiple environment objects. In this case, their `SetUp()`
Packit bd1cd8
will be called in the order they are registered, and their `TearDown()` will be
Packit bd1cd8
called in the reverse order.
Packit bd1cd8
Packit bd1cd8
Note that Google Test takes ownership of the registered environment objects.
Packit bd1cd8
Therefore **do not delete them** by yourself.
Packit bd1cd8
Packit bd1cd8
You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is
Packit bd1cd8
called, probably in `main()`. If you use `gtest_main`, you need to      call
Packit bd1cd8
this before `main()` starts for it to take effect. One way to do this is to
Packit bd1cd8
define a global variable like this:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
However, we strongly recommend you to write your own `main()` and call
Packit bd1cd8
`AddGlobalTestEnvironment()` there, as relying on initialization of global
Packit bd1cd8
variables makes the code harder to read and may cause problems when you
Packit bd1cd8
register multiple environments from different translation units and the
Packit bd1cd8
environments have dependencies among them (remember that the compiler doesn't
Packit bd1cd8
guarantee the order in which global variables from different translation units
Packit bd1cd8
are initialized).
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
# Value Parameterized Tests #
Packit bd1cd8
Packit bd1cd8
_Value-parameterized tests_ allow you to test your code with different
Packit bd1cd8
parameters without writing multiple copies of the same test.
Packit bd1cd8
Packit bd1cd8
Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TEST(MyCodeTest, TestFoo) {
Packit bd1cd8
  // A code to test foo().
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Usually 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.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
void TestFooHelper(bool flag_value) {
Packit bd1cd8
  flag = flag_value;
Packit bd1cd8
  // A code to test foo().
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
TEST(MyCodeTest, TestFoo) {
Packit bd1cd8
  TestFooHelper(false);
Packit bd1cd8
  TestFooHelper(true);
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
But 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?
Packit bd1cd8
Packit bd1cd8
Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values.
Packit bd1cd8
Packit bd1cd8
Here are some other situations when value-parameterized tests come handy:
Packit bd1cd8
Packit bd1cd8
  * You want to test different implementations of an OO interface.
Packit bd1cd8
  * 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!
Packit bd1cd8
Packit bd1cd8
## How to Write Value-Parameterized Tests ##
Packit bd1cd8
Packit bd1cd8
To write value-parameterized tests, first you should define a fixture
Packit bd1cd8
class.  It must be derived from both `::testing::Test` and
Packit bd1cd8
`::testing::WithParamInterface<T>` (the latter is a pure interface),
Packit bd1cd8
where `T` is the type of your parameter values.  For convenience, you
Packit bd1cd8
can just derive the fixture class from `::testing::TestWithParam<T>`,
Packit bd1cd8
which itself is derived from both `::testing::Test` and
Packit bd1cd8
`::testing::WithParamInterface<T>`. `T` can be any copyable type. If
Packit bd1cd8
it's a raw pointer, you are responsible for managing the lifespan of
Packit bd1cd8
the pointed values.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class FooTest : public ::testing::TestWithParam<const char*> {
Packit bd1cd8
  // You can implement all the usual fixture class members here.
Packit bd1cd8
  // To access the test parameter, call GetParam() from class
Packit bd1cd8
  // TestWithParam<T>.
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
// Or, when you want to add parameters to a pre-existing fixture class:
Packit bd1cd8
class BaseTest : public ::testing::Test {
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
class BarTest : public BaseTest,
Packit bd1cd8
                public ::testing::WithParamInterface<const char*> {
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Then, use the `TEST_P` macro to define as many test patterns using
Packit bd1cd8
this fixture as you want.  The `_P` suffix is for "parameterized" or
Packit bd1cd8
"pattern", whichever you prefer to think.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TEST_P(FooTest, DoesBlah) {
Packit bd1cd8
  // Inside a test, access the test parameter with the GetParam() method
Packit bd1cd8
  // of the TestWithParam<T> class:
Packit bd1cd8
  EXPECT_TRUE(foo.Blah(GetParam()));
Packit bd1cd8
  ...
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
TEST_P(FooTest, HasBlahBlah) {
Packit bd1cd8
  ...
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test
Packit bd1cd8
case with any set of parameters you want. Google Test defines a number of
Packit bd1cd8
functions for generating test parameters. They return what we call
Packit bd1cd8
(surprise!) _parameter generators_. Here is a summary of them,
Packit bd1cd8
which are all in the `testing` namespace:
Packit bd1cd8
Packit bd1cd8
| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. |
Packit bd1cd8
|:----------------------------|:------------------------------------------------------------------------------------------------------------------|
Packit bd1cd8
| `Values(v1, v2, ..., vN)`   | Yields values `{v1, v2, ..., vN}`.                                                                                |
Packit bd1cd8
| `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.  |
Packit bd1cd8
| `Bool()`                    | Yields sequence `{false, true}`.                                                                                  |
Packit bd1cd8
| `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. |
Packit bd1cd8
Packit bd1cd8
For more details, see the comments at the definitions of these functions in the [source code](../include/gtest/gtest-param-test.h).
Packit bd1cd8
Packit bd1cd8
The following statement will instantiate tests from the `FooTest` test case
Packit bd1cd8
each with parameter values `"meeny"`, `"miny"`, and `"moe"`.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
INSTANTIATE_TEST_CASE_P(InstantiationName,
Packit bd1cd8
                        FooTest,
Packit bd1cd8
                        ::testing::Values("meeny", "miny", "moe"));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
To distinguish different instances of the pattern (yes, you can
Packit bd1cd8
instantiate it more than once), the first argument to
Packit bd1cd8
`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual
Packit bd1cd8
test case name. Remember to pick unique prefixes for different
Packit bd1cd8
instantiations. The tests from the instantiation above will have these
Packit bd1cd8
names:
Packit bd1cd8
Packit bd1cd8
  * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"`
Packit bd1cd8
  * `InstantiationName/FooTest.DoesBlah/1` for `"miny"`
Packit bd1cd8
  * `InstantiationName/FooTest.DoesBlah/2` for `"moe"`
Packit bd1cd8
  * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"`
Packit bd1cd8
  * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"`
Packit bd1cd8
  * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"`
Packit bd1cd8
Packit bd1cd8
You can use these names in [--gtest\_filter](#running-a-subset-of-the-tests).
Packit bd1cd8
Packit bd1cd8
This statement will instantiate all tests from `FooTest` again, each
Packit bd1cd8
with parameter values `"cat"` and `"dog"`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
const char* pets[] = {"cat", "dog"};
Packit bd1cd8
INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest,
Packit bd1cd8
                        ::testing::ValuesIn(pets));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The tests from the instantiation above will have these names:
Packit bd1cd8
Packit bd1cd8
  * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"`
Packit bd1cd8
  * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"`
Packit bd1cd8
  * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"`
Packit bd1cd8
  * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"`
Packit bd1cd8
Packit bd1cd8
Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_
Packit bd1cd8
tests in the given test case, whether their definitions come before or
Packit bd1cd8
_after_ the `INSTANTIATE_TEST_CASE_P` statement.
Packit bd1cd8
Packit bd1cd8
You can see
Packit bd1cd8
[these](../samples/sample7_unittest.cc)
Packit bd1cd8
[files](../samples/sample8_unittest.cc) for more examples.
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0.
Packit bd1cd8
Packit bd1cd8
## Creating Value-Parameterized Abstract Tests ##
Packit bd1cd8
Packit bd1cd8
In the above, we define and instantiate `FooTest` in the same source
Packit bd1cd8
file. Sometimes you may want to define value-parameterized tests in a
Packit bd1cd8
library and let other people instantiate them later. This pattern is
Packit bd1cd8
known as abstract tests. As an example of its application, when you
Packit bd1cd8
are designing an interface you can write a standard suite of abstract
Packit bd1cd8
tests (perhaps using a factory function as the test parameter) that
Packit bd1cd8
all implementations of the interface are expected to pass. When
Packit bd1cd8
someone implements the interface, he can instantiate your suite to get
Packit bd1cd8
all the interface-conformance tests for free.
Packit bd1cd8
Packit bd1cd8
To define abstract tests, you should organize your code like this:
Packit bd1cd8
Packit bd1cd8
  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.
Packit bd1cd8
  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.
Packit bd1cd8
Packit bd1cd8
Once they are defined, you can instantiate them by including
Packit bd1cd8
`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking
Packit bd1cd8
with `foo_param_test.cc`. You can instantiate the same abstract test
Packit bd1cd8
case multiple times, possibly in different source files.
Packit bd1cd8
Packit bd1cd8
# Typed Tests #
Packit bd1cd8
Packit bd1cd8
Suppose you have multiple implementations of the same interface and
Packit bd1cd8
want to make sure that all of them satisfy some common requirements.
Packit bd1cd8
Or, you may have defined several types that are supposed to conform to
Packit bd1cd8
the same "concept" and you want to verify it.  In both cases, you want
Packit bd1cd8
the same test logic repeated for different types.
Packit bd1cd8
Packit bd1cd8
While you can write one `TEST` or `TEST_F` for each type you want to
Packit bd1cd8
test (and you may even factor the test logic into a function template
Packit bd1cd8
that you invoke from the `TEST`), it's tedious and doesn't scale:
Packit bd1cd8
if you want _m_ tests over _n_ types, you'll end up writing _m\*n_
Packit bd1cd8
`TEST`s.
Packit bd1cd8
Packit bd1cd8
_Typed tests_ allow you to repeat the same test logic over a list of
Packit bd1cd8
types.  You only need to write the test logic once, although you must
Packit bd1cd8
know the type list when writing typed tests.  Here's how you do it:
Packit bd1cd8
Packit bd1cd8
First, define a fixture class template.  It should be parameterized
Packit bd1cd8
by a type.  Remember to derive it from `::testing::Test`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
template <typename T>
Packit bd1cd8
class FooTest : public ::testing::Test {
Packit bd1cd8
 public:
Packit bd1cd8
  ...
Packit bd1cd8
  typedef std::list<T> List;
Packit bd1cd8
  static T shared_;
Packit bd1cd8
  T value_;
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Next, associate a list of types with the test case, which will be
Packit bd1cd8
repeated for each type in the list:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
typedef ::testing::Types<char, int, unsigned int> MyTypes;
Packit bd1cd8
TYPED_TEST_CASE(FooTest, MyTypes);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse
Packit bd1cd8
correctly.  Otherwise the compiler will think that each comma in the
Packit bd1cd8
type list introduces a new macro argument.
Packit bd1cd8
Packit bd1cd8
Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test
Packit bd1cd8
for this test case.  You can repeat this as many times as you want:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TYPED_TEST(FooTest, DoesBlah) {
Packit bd1cd8
  // Inside a test, refer to the special name TypeParam to get the type
Packit bd1cd8
  // parameter.  Since we are inside a derived class template, C++ requires
Packit bd1cd8
  // us to visit the members of FooTest via 'this'.
Packit bd1cd8
  TypeParam n = this->value_;
Packit bd1cd8
Packit bd1cd8
  // To visit static members of the fixture, add the 'TestFixture::'
Packit bd1cd8
  // prefix.
Packit bd1cd8
  n += TestFixture::shared_;
Packit bd1cd8
Packit bd1cd8
  // To refer to typedefs in the fixture, add the 'typename TestFixture::'
Packit bd1cd8
  // prefix.  The 'typename' is required to satisfy the compiler.
Packit bd1cd8
  typename TestFixture::List values;
Packit bd1cd8
  values.push_back(n);
Packit bd1cd8
  ...
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
TYPED_TEST(FooTest, HasPropertyA) { ... }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
You can see `samples/sample6_unittest.cc` for a complete example.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
Packit bd1cd8
since version 1.1.0.
Packit bd1cd8
Packit bd1cd8
# Type-Parameterized Tests #
Packit bd1cd8
Packit bd1cd8
_Type-parameterized tests_ are like typed tests, except that they
Packit bd1cd8
don't require you to know the list of types ahead of time.  Instead,
Packit bd1cd8
you can define the test logic first and instantiate it with different
Packit bd1cd8
type lists later.  You can even instantiate it more than once in the
Packit bd1cd8
same program.
Packit bd1cd8
Packit bd1cd8
If you are designing an interface or concept, you can define a suite
Packit bd1cd8
of type-parameterized tests to verify properties that any valid
Packit bd1cd8
implementation of the interface/concept should have.  Then, the author
Packit bd1cd8
of each implementation can just instantiate the test suite with his
Packit bd1cd8
type to verify that it conforms to the requirements, without having to
Packit bd1cd8
write similar tests repeatedly.  Here's an example:
Packit bd1cd8
Packit bd1cd8
First, define a fixture class template, as we did with typed tests:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
template <typename T>
Packit bd1cd8
class FooTest : public ::testing::Test {
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Next, declare that you will define a type-parameterized test case:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TYPED_TEST_CASE_P(FooTest);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The `_P` suffix is for "parameterized" or "pattern", whichever you
Packit bd1cd8
prefer to think.
Packit bd1cd8
Packit bd1cd8
Then, use `TYPED_TEST_P()` to define a type-parameterized test.  You
Packit bd1cd8
can repeat this as many times as you want:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TYPED_TEST_P(FooTest, DoesBlah) {
Packit bd1cd8
  // Inside a test, refer to TypeParam to get the type parameter.
Packit bd1cd8
  TypeParam n = 0;
Packit bd1cd8
  ...
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
TYPED_TEST_P(FooTest, HasPropertyA) { ... }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Now the tricky part: you need to register all test patterns using the
Packit bd1cd8
`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them.
Packit bd1cd8
The first argument of the macro is the test case name; the rest are
Packit bd1cd8
the names of the tests in this test case:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
REGISTER_TYPED_TEST_CASE_P(FooTest,
Packit bd1cd8
                           DoesBlah, HasPropertyA);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Finally, you are free to instantiate the pattern with the types you
Packit bd1cd8
want.  If you put the above code in a header file, you can `#include`
Packit bd1cd8
it in multiple C++ source files and instantiate it multiple times.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
typedef ::testing::Types<char, int, unsigned int> MyTypes;
Packit bd1cd8
INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
To distinguish different instances of the pattern, the first argument
Packit bd1cd8
to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be
Packit bd1cd8
added to the actual test case name.  Remember to pick unique prefixes
Packit bd1cd8
for different instances.
Packit bd1cd8
Packit bd1cd8
In the special case where the type list contains only one type, you
Packit bd1cd8
can write that type directly without `::testing::Types<...>`, like this:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
You can see `samples/sample6_unittest.cc` for a complete example.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac;
Packit bd1cd8
since version 1.1.0.
Packit bd1cd8
Packit bd1cd8
# Testing Private Code #
Packit bd1cd8
Packit bd1cd8
If you change your software's internal implementation, your tests should not
Packit bd1cd8
break as long as the change is not observable by users. Therefore, per the
Packit bd1cd8
_black-box testing principle_, most of the time you should test your code
Packit bd1cd8
through its public interfaces.
Packit bd1cd8
Packit bd1cd8
If you still find yourself needing to test internal implementation code,
Packit bd1cd8
consider if there's a better design that wouldn't require you to do so. If you
Packit bd1cd8
absolutely have to test non-public interface code though, you can. There are
Packit bd1cd8
two cases to consider:
Packit bd1cd8
Packit bd1cd8
  * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and
Packit bd1cd8
  * Private or protected class members
Packit bd1cd8
Packit bd1cd8
## Static Functions ##
Packit bd1cd8
Packit bd1cd8
Both static functions and definitions/declarations in an unnamed namespace are
Packit bd1cd8
only visible within the same translation unit. To test them, you can `#include`
Packit bd1cd8
the entire `.cc` file being tested in your `*_test.cc` file. (`#include`ing `.cc`
Packit bd1cd8
files is not a good way to reuse code - you should not do this in production
Packit bd1cd8
code!)
Packit bd1cd8
Packit bd1cd8
However, a better approach is to move the private code into the
Packit bd1cd8
`foo::internal` namespace, where `foo` is the namespace your project normally
Packit bd1cd8
uses, and put the private declarations in a `*-internal.h` file. Your
Packit bd1cd8
production `.cc` files and your tests are allowed to include this internal
Packit bd1cd8
header, but your clients are not. This way, you can fully test your internal
Packit bd1cd8
implementation without leaking it to your clients.
Packit bd1cd8
Packit bd1cd8
## Private Class Members ##
Packit bd1cd8
Packit bd1cd8
Private class members are only accessible from within the class or by friends.
Packit bd1cd8
To access a class' private members, you can declare your test fixture as a
Packit bd1cd8
friend to the class and define accessors in your fixture. Tests using the
Packit bd1cd8
fixture can then access the private members of your production class via the
Packit bd1cd8
accessors in the fixture. Note that even though your fixture is a friend to
Packit bd1cd8
your production class, your tests are not automatically friends to it, as they
Packit bd1cd8
are technically defined in sub-classes of the fixture.
Packit bd1cd8
Packit bd1cd8
Another way to test private members is to refactor them into an implementation
Packit bd1cd8
class, which is then declared in a `*-internal.h` file. Your clients aren't
Packit bd1cd8
allowed to include this header but your tests can. Such is called the Pimpl
Packit bd1cd8
(Private Implementation) idiom.
Packit bd1cd8
Packit bd1cd8
Or, you can declare an individual test as a friend of your class by adding this
Packit bd1cd8
line in the class body:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
FRIEND_TEST(TestCaseName, TestName);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
For example,
Packit bd1cd8
```
Packit bd1cd8
// foo.h
Packit bd1cd8
#include "gtest/gtest_prod.h"
Packit bd1cd8
Packit bd1cd8
// Defines FRIEND_TEST.
Packit bd1cd8
class Foo {
Packit bd1cd8
  ...
Packit bd1cd8
 private:
Packit bd1cd8
  FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
Packit bd1cd8
  int Bar(void* x);
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
// foo_test.cc
Packit bd1cd8
...
Packit bd1cd8
TEST(FooTest, BarReturnsZeroOnNull) {
Packit bd1cd8
  Foo foo;
Packit bd1cd8
  EXPECT_EQ(0, foo.Bar(NULL));
Packit bd1cd8
  // Uses Foo's private member Bar().
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Pay special attention when your class is defined in a namespace, as you should
Packit bd1cd8
define your test fixtures and tests in the same namespace if you want them to
Packit bd1cd8
be friends of your class. For example, if the code to be tested looks like:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
namespace my_namespace {
Packit bd1cd8
Packit bd1cd8
class Foo {
Packit bd1cd8
  friend class FooTest;
Packit bd1cd8
  FRIEND_TEST(FooTest, Bar);
Packit bd1cd8
  FRIEND_TEST(FooTest, Baz);
Packit bd1cd8
  ...
Packit bd1cd8
  definition of the class Foo
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
}  // namespace my_namespace
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Your test code should be something like:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
namespace my_namespace {
Packit bd1cd8
class FooTest : public ::testing::Test {
Packit bd1cd8
 protected:
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
TEST_F(FooTest, Bar) { ... }
Packit bd1cd8
TEST_F(FooTest, Baz) { ... }
Packit bd1cd8
Packit bd1cd8
}  // namespace my_namespace
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
# Catching Failures #
Packit bd1cd8
Packit bd1cd8
If you are building a testing utility on top of Google Test, you'll
Packit bd1cd8
want to test your utility.  What framework would you use to test it?
Packit bd1cd8
Google Test, of course.
Packit bd1cd8
Packit bd1cd8
The challenge is to verify that your testing utility reports failures
Packit bd1cd8
correctly.  In frameworks that report a failure by throwing an
Packit bd1cd8
exception, you could catch the exception and assert on it.  But Google
Packit bd1cd8
Test doesn't use exceptions, so how do we test that a piece of code
Packit bd1cd8
generates an expected failure?
Packit bd1cd8
Packit bd1cd8
`"gtest/gtest-spi.h"` contains some constructs to do this.  After 
Packit bd1cd8
`#include`ing this header, you can use
Packit bd1cd8
Packit bd1cd8
| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` |
Packit bd1cd8
|:--------------------------------------------------|
Packit bd1cd8
Packit bd1cd8
to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure
Packit bd1cd8
whose message contains the given _substring_, or use
Packit bd1cd8
Packit bd1cd8
| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` |
Packit bd1cd8
|:-----------------------------------------------------|
Packit bd1cd8
Packit bd1cd8
if you are expecting a non-fatal (e.g. `EXPECT_*`) failure.
Packit bd1cd8
Packit bd1cd8
For technical reasons, there are some caveats:
Packit bd1cd8
Packit bd1cd8
  1. You cannot stream a failure message to either macro.
Packit bd1cd8
  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object.
Packit bd1cd8
  1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value.
Packit bd1cd8
Packit bd1cd8
_Note:_ Google Test is designed with threads in mind. Once the
Packit bd1cd8
synchronization primitives in `"gtest/internal/gtest-port.h"` have
Packit bd1cd8
been implemented, Google Test will become thread-safe, meaning that
Packit bd1cd8
you can then use assertions in multiple threads concurrently. Before
Packit bd1cd8
that, however, Google Test only supports single-threaded usage. Once
Packit bd1cd8
thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()`
Packit bd1cd8
will capture failures in the current thread only. If _statement_
Packit bd1cd8
creates new threads, failures in these threads will be ignored. If
Packit bd1cd8
you want to capture failures from all threads instead, you should use
Packit bd1cd8
the following macros:
Packit bd1cd8
Packit bd1cd8
| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
Packit bd1cd8
|:-----------------------------------------------------------------|
Packit bd1cd8
| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` |
Packit bd1cd8
Packit bd1cd8
# Getting the Current Test's Name #
Packit bd1cd8
Packit bd1cd8
Sometimes a function may need to know the name of the currently running test.
Packit bd1cd8
For example, you may be using the `SetUp()` method of your test fixture to set
Packit bd1cd8
the golden file name based on which test is running. The `::testing::TestInfo`
Packit bd1cd8
class has this information:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
namespace testing {
Packit bd1cd8
Packit bd1cd8
class TestInfo {
Packit bd1cd8
 public:
Packit bd1cd8
  // Returns the test case name and the test name, respectively.
Packit bd1cd8
  //
Packit bd1cd8
  // Do NOT delete or free the return value - it's managed by the
Packit bd1cd8
  // TestInfo class.
Packit bd1cd8
  const char* test_case_name() const;
Packit bd1cd8
  const char* name() const;
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
}  // namespace testing
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
> To obtain a `TestInfo` object for the currently running test, call
Packit bd1cd8
`current_test_info()` on the `UnitTest` singleton object:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
// Gets information about the currently running test.
Packit bd1cd8
// Do NOT delete the returned object - it's managed by the UnitTest class.
Packit bd1cd8
const ::testing::TestInfo* const test_info =
Packit bd1cd8
  ::testing::UnitTest::GetInstance()->current_test_info();
Packit bd1cd8
printf("We are in test %s of test case %s.\n",
Packit bd1cd8
       test_info->name(), test_info->test_case_name());
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
`current_test_info()` returns a null pointer if no test is running. In
Packit bd1cd8
particular, you cannot find the test case name in `TestCaseSetUp()`,
Packit bd1cd8
`TestCaseTearDown()` (where you know the test case name implicitly), or
Packit bd1cd8
functions called from them.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
# Extending Google Test by Handling Test Events #
Packit bd1cd8
Packit bd1cd8
Google Test provides an event listener API to let you receive
Packit bd1cd8
notifications about the progress of a test program and test
Packit bd1cd8
failures. The events you can listen to include the start and end of
Packit bd1cd8
the test program, a test case, or a test method, among others. You may
Packit bd1cd8
use this API to augment or replace the standard console output,
Packit bd1cd8
replace the XML output, or provide a completely different form of
Packit bd1cd8
output, such as a GUI or a database. You can also use test events as
Packit bd1cd8
checkpoints to implement a resource leak checker, for example.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac; since v1.4.0.
Packit bd1cd8
Packit bd1cd8
## Defining Event Listeners ##
Packit bd1cd8
Packit bd1cd8
To define a event listener, you subclass either
Packit bd1cd8
[testing::TestEventListener](../include/gtest/gtest.h#L991)
Packit bd1cd8
or [testing::EmptyTestEventListener](../include/gtest/gtest.h#L1044).
Packit bd1cd8
The former is an (abstract) interface, where each pure virtual method
Packit bd1cd8
can be overridden to handle a test event (For example, when a test
Packit bd1cd8
starts, the `OnTestStart()` method will be called.). The latter provides
Packit bd1cd8
an empty implementation of all methods in the interface, such that a
Packit bd1cd8
subclass only needs to override the methods it cares about.
Packit bd1cd8
Packit bd1cd8
When an event is fired, its context is passed to the handler function
Packit bd1cd8
as an argument. The following argument types are used:
Packit bd1cd8
  * [UnitTest](../include/gtest/gtest.h#L1151) reflects the state of the entire test program,
Packit bd1cd8
  * [TestCase](../include/gtest/gtest.h#L778) has information about a test case, which can contain one or more tests,
Packit bd1cd8
  * [TestInfo](../include/gtest/gtest.h#L644) contains the state of a test, and
Packit bd1cd8
  * [TestPartResult](../include/gtest/gtest-test-part.h#L47) represents the result of a test assertion.
Packit bd1cd8
Packit bd1cd8
An event handler function can examine the argument it receives to find
Packit bd1cd8
out interesting information about the event and the test program's
Packit bd1cd8
state.  Here's an example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  class MinimalistPrinter : public ::testing::EmptyTestEventListener {
Packit bd1cd8
    // Called before a test starts.
Packit bd1cd8
    virtual void OnTestStart(const ::testing::TestInfo& test_info) {
Packit bd1cd8
      printf("*** Test %s.%s starting.\n",
Packit bd1cd8
             test_info.test_case_name(), test_info.name());
Packit bd1cd8
    }
Packit bd1cd8
Packit bd1cd8
    // Called after a failed assertion or a SUCCEED() invocation.
Packit bd1cd8
    virtual void OnTestPartResult(
Packit bd1cd8
        const ::testing::TestPartResult& test_part_result) {
Packit bd1cd8
      printf("%s in %s:%d\n%s\n",
Packit bd1cd8
             test_part_result.failed() ? "*** Failure" : "Success",
Packit bd1cd8
             test_part_result.file_name(),
Packit bd1cd8
             test_part_result.line_number(),
Packit bd1cd8
             test_part_result.summary());
Packit bd1cd8
    }
Packit bd1cd8
Packit bd1cd8
    // Called after a test ends.
Packit bd1cd8
    virtual void OnTestEnd(const ::testing::TestInfo& test_info) {
Packit bd1cd8
      printf("*** Test %s.%s ending.\n",
Packit bd1cd8
             test_info.test_case_name(), test_info.name());
Packit bd1cd8
    }
Packit bd1cd8
  };
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Using Event Listeners ##
Packit bd1cd8
Packit bd1cd8
To use the event listener you have defined, add an instance of it to
Packit bd1cd8
the Google Test event listener list (represented by class
Packit bd1cd8
[TestEventListeners](../include/gtest/gtest.h#L1064)
Packit bd1cd8
- note the "s" at the end of the name) in your
Packit bd1cd8
`main()` function, before calling `RUN_ALL_TESTS()`:
Packit bd1cd8
```
Packit bd1cd8
int main(int argc, char** argv) {
Packit bd1cd8
  ::testing::InitGoogleTest(&argc, argv);
Packit bd1cd8
  // Gets hold of the event listener list.
Packit bd1cd8
  ::testing::TestEventListeners& listeners =
Packit bd1cd8
      ::testing::UnitTest::GetInstance()->listeners();
Packit bd1cd8
  // Adds a listener to the end.  Google Test takes the ownership.
Packit bd1cd8
  listeners.Append(new MinimalistPrinter);
Packit bd1cd8
  return RUN_ALL_TESTS();
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
There's only one problem: the default test result printer is still in
Packit bd1cd8
effect, so its output will mingle with the output from your minimalist
Packit bd1cd8
printer. To suppress the default printer, just release it from the
Packit bd1cd8
event listener list and delete it. You can do so by adding one line:
Packit bd1cd8
```
Packit bd1cd8
  ...
Packit bd1cd8
  delete listeners.Release(listeners.default_result_printer());
Packit bd1cd8
  listeners.Append(new MinimalistPrinter);
Packit bd1cd8
  return RUN_ALL_TESTS();
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Now, sit back and enjoy a completely different output from your
Packit bd1cd8
tests. For more details, you can read this
Packit bd1cd8
[sample](../samples/sample9_unittest.cc).
Packit bd1cd8
Packit bd1cd8
You may append more than one listener to the list. When an `On*Start()`
Packit bd1cd8
or `OnTestPartResult()` event is fired, the listeners will receive it in
Packit bd1cd8
the order they appear in the list (since new listeners are added to
Packit bd1cd8
the end of the list, the default text printer and the default XML
Packit bd1cd8
generator will receive the event first). An `On*End()` event will be
Packit bd1cd8
received by the listeners in the _reverse_ order. This allows output by
Packit bd1cd8
listeners added later to be framed by output from listeners added
Packit bd1cd8
earlier.
Packit bd1cd8
Packit bd1cd8
## Generating Failures in Listeners ##
Packit bd1cd8
Packit bd1cd8
You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`,
Packit bd1cd8
`FAIL()`, etc) when processing an event. There are some restrictions:
Packit bd1cd8
Packit bd1cd8
  1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively).
Packit bd1cd8
  1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure.
Packit bd1cd8
Packit bd1cd8
When you add listeners to the listener list, you should put listeners
Packit bd1cd8
that handle `OnTestPartResult()` _before_ listeners that can generate
Packit bd1cd8
failures. This ensures that failures generated by the latter are
Packit bd1cd8
attributed to the right test by the former.
Packit bd1cd8
Packit bd1cd8
We have a sample of failure-raising listener
Packit bd1cd8
[here](../samples/sample10_unittest.cc).
Packit bd1cd8
Packit bd1cd8
# Running Test Programs: Advanced Options #
Packit bd1cd8
Packit bd1cd8
Google Test test programs are ordinary executables. Once built, you can run
Packit bd1cd8
them directly and affect their behavior via the following environment variables
Packit bd1cd8
and/or command line flags. For the flags to work, your programs must call
Packit bd1cd8
`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
Packit bd1cd8
Packit bd1cd8
To see a list of supported flags and their usage, please run your test
Packit bd1cd8
program with the `--help` flag.  You can also use `-h`, `-?`, or `/?`
Packit bd1cd8
for short.  This feature is added in version 1.3.0.
Packit bd1cd8
Packit bd1cd8
If an option is specified both by an environment variable and by a
Packit bd1cd8
flag, the latter takes precedence.  Most of the options can also be
Packit bd1cd8
set/read in code: to access the value of command line flag
Packit bd1cd8
`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`.  A common pattern is
Packit bd1cd8
to set the value of a flag before calling `::testing::InitGoogleTest()`
Packit bd1cd8
to change the default value of the flag:
Packit bd1cd8
```
Packit bd1cd8
int main(int argc, char** argv) {
Packit bd1cd8
  // Disables elapsed time by default.
Packit bd1cd8
  ::testing::GTEST_FLAG(print_time) = false;
Packit bd1cd8
Packit bd1cd8
  // This allows the user to override the flag on the command line.
Packit bd1cd8
  ::testing::InitGoogleTest(&argc, argv);
Packit bd1cd8
Packit bd1cd8
  return RUN_ALL_TESTS();
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Selecting Tests ##
Packit bd1cd8
Packit bd1cd8
This section shows various options for choosing which tests to run.
Packit bd1cd8
Packit bd1cd8
### Listing Test Names ###
Packit bd1cd8
Packit bd1cd8
Sometimes it is necessary to list the available tests in a program before
Packit bd1cd8
running them so that a filter may be applied if needed. Including the flag
Packit bd1cd8
`--gtest_list_tests` overrides all other flags and lists tests in the following
Packit bd1cd8
format:
Packit bd1cd8
```
Packit bd1cd8
TestCase1.
Packit bd1cd8
  TestName1
Packit bd1cd8
  TestName2
Packit bd1cd8
TestCase2.
Packit bd1cd8
  TestName
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
None of the tests listed are actually run if the flag is provided. There is no
Packit bd1cd8
corresponding environment variable for this flag.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
### Running a Subset of the Tests ###
Packit bd1cd8
Packit bd1cd8
By default, a Google Test program runs all tests the user has defined.
Packit bd1cd8
Sometimes, you want to run only a subset of the tests (e.g. for debugging or
Packit bd1cd8
quickly verifying a change). If you set the `GTEST_FILTER` environment variable
Packit bd1cd8
or the `--gtest_filter` flag to a filter string, Google Test will only run the
Packit bd1cd8
tests whose full names (in the form of `TestCaseName.TestName`) match the
Packit bd1cd8
filter.
Packit bd1cd8
Packit bd1cd8
The format of a filter is a '`:`'-separated list of wildcard patterns (called
Packit bd1cd8
the positive patterns) optionally followed by a '`-`' and another
Packit bd1cd8
'`:`'-separated pattern list (called the negative patterns). A test matches the
Packit bd1cd8
filter if and only if it matches any of the positive patterns but does not
Packit bd1cd8
match any of the negative patterns.
Packit bd1cd8
Packit bd1cd8
A pattern may contain `'*'` (matches any string) or `'?'` (matches any single
Packit bd1cd8
character). For convenience, the filter `'*-NegativePatterns'` can be also
Packit bd1cd8
written as `'-NegativePatterns'`.
Packit bd1cd8
Packit bd1cd8
For example:
Packit bd1cd8
Packit bd1cd8
  * `./foo_test` Has no flag, and thus runs all its tests.
Packit bd1cd8
  * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value.
Packit bd1cd8
  * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`.
Packit bd1cd8
  * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`.
Packit bd1cd8
  * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests.
Packit bd1cd8
  * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
### Temporarily Disabling Tests ###
Packit bd1cd8
Packit bd1cd8
If you have a broken test that you cannot fix right away, you can add the
Packit bd1cd8
`DISABLED_` prefix to its name. This will exclude it from execution. This is
Packit bd1cd8
better than commenting out the code or using `#if 0`, as disabled tests are
Packit bd1cd8
still compiled (and thus won't rot).
Packit bd1cd8
Packit bd1cd8
If you need to disable all tests in a test case, you can either add `DISABLED_`
Packit bd1cd8
to the front of the name of each test, or alternatively add it to the front of
Packit bd1cd8
the test case name.
Packit bd1cd8
Packit bd1cd8
For example, the following tests won't be run by Google Test, even though they
Packit bd1cd8
will still be compiled:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
// Tests that Foo does Abc.
Packit bd1cd8
TEST(FooTest, DISABLED_DoesAbc) { ... }
Packit bd1cd8
Packit bd1cd8
class DISABLED_BarTest : public ::testing::Test { ... };
Packit bd1cd8
Packit bd1cd8
// Tests that Bar does Xyz.
Packit bd1cd8
TEST_F(DISABLED_BarTest, DoesXyz) { ... }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
_Note:_ This feature should only be used for temporary pain-relief. You still
Packit bd1cd8
have to fix the disabled tests at a later date. As a reminder, Google Test will
Packit bd1cd8
print a banner warning you if a test program contains any disabled tests.
Packit bd1cd8
Packit bd1cd8
_Tip:_ You can easily count the number of disabled tests you have
Packit bd1cd8
using `grep`. This number can be used as a metric for improving your
Packit bd1cd8
test quality.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
### Temporarily Enabling Disabled Tests ###
Packit bd1cd8
Packit bd1cd8
To include [disabled tests](#temporarily-disabling-tests) in test
Packit bd1cd8
execution, just invoke the test program with the
Packit bd1cd8
`--gtest_also_run_disabled_tests` flag or set the
Packit bd1cd8
`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other
Packit bd1cd8
than `0`.  You can combine this with the
Packit bd1cd8
[--gtest\_filter](#running-a-subset-of-the-tests) flag to further select
Packit bd1cd8
which disabled tests to run.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac; since version 1.3.0.
Packit bd1cd8
Packit bd1cd8
## Repeating the Tests ##
Packit bd1cd8
Packit bd1cd8
Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it
Packit bd1cd8
will fail only 1% of the time, making it rather hard to reproduce the bug under
Packit bd1cd8
a debugger. This can be a major source of frustration.
Packit bd1cd8
Packit bd1cd8
The `--gtest_repeat` flag allows you to repeat all (or selected) test methods
Packit bd1cd8
in a program many times. Hopefully, a flaky test will eventually fail and give
Packit bd1cd8
you a chance to debug. Here's how to use it:
Packit bd1cd8
Packit bd1cd8
| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. |
Packit bd1cd8
|:---------------------------------|:--------------------------------------------------------|
Packit bd1cd8
| `$ foo_test --gtest_repeat=-1`   | A negative count means repeating forever.               |
Packit bd1cd8
| `$ 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. |
Packit bd1cd8
| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. |
Packit bd1cd8
Packit bd1cd8
If your test program contains global set-up/tear-down code registered
Packit bd1cd8
using `AddGlobalTestEnvironment()`, it will be repeated in each
Packit bd1cd8
iteration as well, as the flakiness may be in it. You can also specify
Packit bd1cd8
the repeat count by setting the `GTEST_REPEAT` environment variable.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
## Shuffling the Tests ##
Packit bd1cd8
Packit bd1cd8
You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`
Packit bd1cd8
environment variable to `1`) to run the tests in a program in a random
Packit bd1cd8
order. This helps to reveal bad dependencies between tests.
Packit bd1cd8
Packit bd1cd8
By default, Google Test uses a random seed calculated from the current
Packit bd1cd8
time. Therefore you'll get a different order every time. The console
Packit bd1cd8
output includes the random seed value, such that you can reproduce an
Packit bd1cd8
order-related test failure later. To specify the random seed
Packit bd1cd8
explicitly, use the `--gtest_random_seed=SEED` flag (or set the
Packit bd1cd8
`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer
Packit bd1cd8
between 0 and 99999. The seed value 0 is special: it tells Google Test
Packit bd1cd8
to do the default behavior of calculating the seed from the current
Packit bd1cd8
time.
Packit bd1cd8
Packit bd1cd8
If you combine this with `--gtest_repeat=N`, Google Test will pick a
Packit bd1cd8
different random seed and re-shuffle the tests in each iteration.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac; since v1.4.0.
Packit bd1cd8
Packit bd1cd8
## Controlling Test Output ##
Packit bd1cd8
Packit bd1cd8
This section teaches how to tweak the way test results are reported.
Packit bd1cd8
Packit bd1cd8
### Colored Terminal Output ###
Packit bd1cd8
Packit bd1cd8
Google Test can use colors in its terminal output to make it easier to spot
Packit bd1cd8
the separation between tests, and whether tests passed.
Packit bd1cd8
Packit bd1cd8
You can set the GTEST\_COLOR environment variable or set the `--gtest_color`
Packit bd1cd8
command line flag to `yes`, `no`, or `auto` (the default) to enable colors,
Packit bd1cd8
disable colors, or let Google Test decide. When the value is `auto`, Google
Packit bd1cd8
Test will use colors if and only if the output goes to a terminal and (on
Packit bd1cd8
non-Windows platforms) the `TERM` environment variable is set to `xterm` or
Packit bd1cd8
`xterm-color`.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
### Suppressing the Elapsed Time ###
Packit bd1cd8
Packit bd1cd8
By default, Google Test prints the time it takes to run each test.  To
Packit bd1cd8
suppress that, run the test program with the `--gtest_print_time=0`
Packit bd1cd8
command line flag.  Setting the `GTEST_PRINT_TIME` environment
Packit bd1cd8
variable to `0` has the same effect.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.  (In Google Test 1.3.0 and lower,
Packit bd1cd8
the default behavior is that the elapsed time is **not** printed.)
Packit bd1cd8
Packit bd1cd8
### Generating an XML Report ###
Packit bd1cd8
Packit bd1cd8
Google Test can emit a detailed XML report to a file in addition to its normal
Packit bd1cd8
textual output. The report contains the duration of each test, and thus can
Packit bd1cd8
help you identify slow tests.
Packit bd1cd8
Packit bd1cd8
To generate the XML report, set the `GTEST_OUTPUT` environment variable or the
Packit bd1cd8
`--gtest_output` flag to the string `"xml:_path_to_output_file_"`, which will
Packit bd1cd8
create the file at the given location. You can also just use the string
Packit bd1cd8
`"xml"`, in which case the output can be found in the `test_detail.xml` file in
Packit bd1cd8
the current directory.
Packit bd1cd8
Packit bd1cd8
If you specify a directory (for example, `"xml:output/directory/"` on Linux or
Packit bd1cd8
`"xml:output\directory\"` on Windows), Google Test will create the XML file in
Packit bd1cd8
that directory, named after the test executable (e.g. `foo_test.xml` for test
Packit bd1cd8
program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left
Packit bd1cd8
over from a previous run), Google Test will pick a different name (e.g.
Packit bd1cd8
`foo_test_1.xml`) to avoid overwriting it.
Packit bd1cd8
Packit bd1cd8
The report uses the format described here.  It is based on the
Packit bd1cd8
`junitreport` Ant task and can be parsed by popular continuous build
Packit bd1cd8
systems like [Hudson](https://hudson.dev.java.net/). Since that format
Packit bd1cd8
was originally intended for Java, a little interpretation is required
Packit bd1cd8
to make it apply to Google Test tests, as shown here:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
<testsuites name="AllTests" ...>
Packit bd1cd8
  <testsuite name="test_case_name" ...>
Packit bd1cd8
    <testcase name="test_name" ...>
Packit bd1cd8
      <failure message="..."/>
Packit bd1cd8
      <failure message="..."/>
Packit bd1cd8
      <failure message="..."/>
Packit bd1cd8
    </testcase>
Packit bd1cd8
  </testsuite>
Packit bd1cd8
</testsuites>
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
  * The root `<testsuites>` element corresponds to the entire test program.
Packit bd1cd8
  * `<testsuite>` elements correspond to Google Test test cases.
Packit bd1cd8
  * `<testcase>` elements correspond to Google Test test functions.
Packit bd1cd8
Packit bd1cd8
For instance, the following program
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TEST(MathTest, Addition) { ... }
Packit bd1cd8
TEST(MathTest, Subtraction) { ... }
Packit bd1cd8
TEST(LogicTest, NonContradiction) { ... }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
could generate this report:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
<testsuites tests="3" failures="1" errors="0" time="35" name="AllTests">
Packit bd1cd8
  <testsuite name="MathTest" tests="2" failures="1" errors="0" time="15">
Packit bd1cd8
    <testcase name="Addition" status="run" time="7" classname="">
Packit bd1cd8
      <failure message="Value of: add(1, 1)
 Actual: 3
Expected: 2" type=""/>
Packit bd1cd8
      <failure message="Value of: add(1, -1)
 Actual: 1
Expected: 0" type=""/>
Packit bd1cd8
    </testcase>
Packit bd1cd8
    <testcase name="Subtraction" status="run" time="5" classname="">
Packit bd1cd8
    </testcase>
Packit bd1cd8
  </testsuite>
Packit bd1cd8
  <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5">
Packit bd1cd8
    <testcase name="NonContradiction" status="run" time="5" classname="">
Packit bd1cd8
    </testcase>
Packit bd1cd8
  </testsuite>
Packit bd1cd8
</testsuites>
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Things to note:
Packit bd1cd8
Packit bd1cd8
  * 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.
Packit bd1cd8
  * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds.
Packit bd1cd8
  * Each `<failure>` element corresponds to a single failed Google Test assertion.
Packit bd1cd8
  * 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.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
## Controlling How Failures Are Reported ##
Packit bd1cd8
Packit bd1cd8
### Turning Assertion Failures into Break-Points ###
Packit bd1cd8
Packit bd1cd8
When running test programs under a debugger, it's very convenient if the
Packit bd1cd8
debugger can catch an assertion failure and automatically drop into interactive
Packit bd1cd8
mode. Google Test's _break-on-failure_ mode supports this behavior.
Packit bd1cd8
Packit bd1cd8
To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value
Packit bd1cd8
other than `0` . Alternatively, you can use the `--gtest_break_on_failure`
Packit bd1cd8
command line flag.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
### Disabling Catching Test-Thrown Exceptions ###
Packit bd1cd8
Packit bd1cd8
Google Test can be used either with or without exceptions enabled.  If
Packit bd1cd8
a test throws a C++ exception or (on Windows) a structured exception
Packit bd1cd8
(SEH), by default Google Test catches it, reports it as a test
Packit bd1cd8
failure, and continues with the next test method.  This maximizes the
Packit bd1cd8
coverage of a test run.  Also, on Windows an uncaught exception will
Packit bd1cd8
cause a pop-up window, so catching the exceptions allows you to run
Packit bd1cd8
the tests automatically.
Packit bd1cd8
Packit bd1cd8
When debugging the test failures, however, you may instead want the
Packit bd1cd8
exceptions to be handled by the debugger, such that you can examine
Packit bd1cd8
the call stack when an exception is thrown.  To achieve that, set the
Packit bd1cd8
`GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the
Packit bd1cd8
`--gtest_catch_exceptions=0` flag when running the tests.
Packit bd1cd8
Packit bd1cd8
**Availability**: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
### Letting Another Testing Framework Drive ###
Packit bd1cd8
Packit bd1cd8
If you work on a project that has already been using another testing
Packit bd1cd8
framework and is not ready to completely switch to Google Test yet,
Packit bd1cd8
you can get much of Google Test's benefit by using its assertions in
Packit bd1cd8
your existing tests.  Just change your `main()` function to look
Packit bd1cd8
like:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
#include "gtest/gtest.h"
Packit bd1cd8
Packit bd1cd8
int main(int argc, char** argv) {
Packit bd1cd8
  ::testing::GTEST_FLAG(throw_on_failure) = true;
Packit bd1cd8
  // Important: Google Test must be initialized.
Packit bd1cd8
  ::testing::InitGoogleTest(&argc, argv);
Packit bd1cd8
Packit bd1cd8
  ... whatever your existing testing framework requires ...
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
With that, you can use Google Test assertions in addition to the
Packit bd1cd8
native assertions your testing framework provides, for example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
void TestFooDoesBar() {
Packit bd1cd8
  Foo foo;
Packit bd1cd8
  EXPECT_LE(foo.Bar(1), 100);     // A Google Test assertion.
Packit bd1cd8
  CPPUNIT_ASSERT(foo.IsEmpty());  // A native assertion.
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
If a Google Test assertion fails, it will print an error message and
Packit bd1cd8
throw an exception, which will be treated as a failure by your host
Packit bd1cd8
testing framework.  If you compile your code with exceptions disabled,
Packit bd1cd8
a failed Google Test assertion will instead exit your program with a
Packit bd1cd8
non-zero code, which will also signal a test failure to your test
Packit bd1cd8
runner.
Packit bd1cd8
Packit bd1cd8
If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in
Packit bd1cd8
your `main()`, you can alternatively enable this feature by specifying
Packit bd1cd8
the `--gtest_throw_on_failure` flag on the command-line or setting the
Packit bd1cd8
`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value.
Packit bd1cd8
Packit bd1cd8
Death tests are _not_ supported when other test framework is used to organize tests.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac; since v1.3.0.
Packit bd1cd8
Packit bd1cd8
## Distributing Test Functions to Multiple Machines ##
Packit bd1cd8
Packit bd1cd8
If you have more than one machine you can use to run a test program,
Packit bd1cd8
you might want to run the test functions in parallel and get the
Packit bd1cd8
result faster.  We call this technique _sharding_, where each machine
Packit bd1cd8
is called a _shard_.
Packit bd1cd8
Packit bd1cd8
Google Test is compatible with test sharding.  To take advantage of
Packit bd1cd8
this feature, your test runner (not part of Google Test) needs to do
Packit bd1cd8
the following:
Packit bd1cd8
Packit bd1cd8
  1. Allocate a number of machines (shards) to run the tests.
Packit bd1cd8
  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.
Packit bd1cd8
  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]`.
Packit bd1cd8
  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.
Packit bd1cd8
  1. Wait for all shards to finish, then collect and report the results.
Packit bd1cd8
Packit bd1cd8
Your project may have tests that were written without Google Test and
Packit bd1cd8
thus don't understand this protocol.  In order for your test runner to
Packit bd1cd8
figure out which test supports sharding, it can set the environment
Packit bd1cd8
variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path.  If a
Packit bd1cd8
test program supports sharding, it will create this file to
Packit bd1cd8
acknowledge the fact (the actual contents of the file are not
Packit bd1cd8
important at this time; although we may stick some useful information
Packit bd1cd8
in it in the future.); otherwise it will not create it.
Packit bd1cd8
Packit bd1cd8
Here's an example to make it clear.  Suppose you have a test program
Packit bd1cd8
`foo_test` that contains the following 5 test functions:
Packit bd1cd8
```
Packit bd1cd8
TEST(A, V)
Packit bd1cd8
TEST(A, W)
Packit bd1cd8
TEST(B, X)
Packit bd1cd8
TEST(B, Y)
Packit bd1cd8
TEST(B, Z)
Packit bd1cd8
```
Packit bd1cd8
and you have 3 machines at your disposal.  To run the test functions in
Packit bd1cd8
parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and
Packit bd1cd8
set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively.
Packit bd1cd8
Then you would run the same `foo_test` on each machine.
Packit bd1cd8
Packit bd1cd8
Google Test reserves the right to change how the work is distributed
Packit bd1cd8
across the shards, but here's one possible scenario:
Packit bd1cd8
Packit bd1cd8
  * Machine #0 runs `A.V` and `B.X`.
Packit bd1cd8
  * Machine #1 runs `A.W` and `B.Y`.
Packit bd1cd8
  * Machine #2 runs `B.Z`.
Packit bd1cd8
Packit bd1cd8
_Availability:_ Linux, Windows, Mac; since version 1.3.0.
Packit bd1cd8
Packit bd1cd8
# Fusing Google Test Source Files #
Packit bd1cd8
Packit bd1cd8
Google Test's implementation consists of ~30 files (excluding its own
Packit bd1cd8
tests).  Sometimes you may want them to be packaged up in two files (a
Packit bd1cd8
`.h` and a `.cc`) instead, such that you can easily copy them to a new
Packit bd1cd8
machine and start hacking there.  For this we provide an experimental
Packit bd1cd8
Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0).
Packit bd1cd8
Assuming you have Python 2.4 or above installed on your machine, just
Packit bd1cd8
go to that directory and run
Packit bd1cd8
```
Packit bd1cd8
python fuse_gtest_files.py OUTPUT_DIR
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
and you should see an `OUTPUT_DIR` directory being created with files
Packit bd1cd8
`gtest/gtest.h` and `gtest/gtest-all.cc` in it.  These files contain
Packit bd1cd8
everything you need to use Google Test.  Just copy them to anywhere
Packit bd1cd8
you want and you are ready to write tests.  You can use the
Packit bd1cd8
[scripts/test/Makefile](../scripts/test/Makefile)
Packit bd1cd8
file as an example on how to compile your tests against them.
Packit bd1cd8
Packit bd1cd8
# Where to Go from Here #
Packit bd1cd8
Packit bd1cd8
Congratulations! You've now learned more advanced Google Test tools and are
Packit bd1cd8
ready to tackle more complex testing tasks. If you want to dive even deeper, you
Packit bd1cd8
can read the [Frequently-Asked Questions](FAQ.md).