Now that you have read [Primer](V1_5_Primer.md) and learned how to write tests
using Google Test, it's time to learn some new tricks. This document
will show you more assertions as well as how to construct complex
failure messages, propagate fatal failures, reuse and speed up your
test fixtures, and use various flags with your tests.
# More Assertions #
This section covers some less frequently used, but still significant,
assertions.
## Explicit Success and Failure ##
These three assertions do not actually test a value or expression. Instead,
they generate a success or failure directly. Like the macros that actually
perform a test, you may stream a custom failure message into the them.
| `SUCCEED();` |
|:-------------|
Generates a success. This does NOT make the overall test succeed. A test is
considered successful only if none of its assertions fail during its execution.
Note: `SUCCEED()` is purely documentary and currently doesn't generate any
user-visible output. However, we may add `SUCCEED()` messages to Google Test's
output in the future.
| `FAIL();` | `ADD_FAILURE();` |
|:-----------|:-----------------|
`FAIL*` generates a fatal failure while `ADD_FAILURE*` generates a nonfatal
failure. These are useful when control flow, rather than a Boolean expression,
deteremines the test's success or failure. For example, you might want to write
something like:
```
switch(expression) {
case 1: ... some checks ...
case 2: ... some other checks
...
default: FAIL() << "We shouldn't get here.";
}
```
_Availability_: Linux, Windows, Mac.
## Exception Assertions ##
These are for verifying that a piece of code throws (or does not
throw) an exception of the given type:
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_THROW(`_statement_, _exception\_type_`);` | `EXPECT_THROW(`_statement_, _exception\_type_`);` | _statement_ throws an exception of the given type |
| `ASSERT_ANY_THROW(`_statement_`);` | `EXPECT_ANY_THROW(`_statement_`);` | _statement_ throws an exception of any type |
| `ASSERT_NO_THROW(`_statement_`);` | `EXPECT_NO_THROW(`_statement_`);` | _statement_ doesn't throw any exception |
Examples:
```
ASSERT_THROW(Foo(5), bar_exception);
EXPECT_NO_THROW({
int n = 5;
Bar(&n);
});
```
_Availability_: Linux, Windows, Mac; since version 1.1.0.
## Predicate Assertions for Better Error Messages ##
Even though Google Test has a rich set of assertions, they can never be
complete, as it's impossible (nor a good idea) to anticipate all the scenarios
a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()`
to check a complex expression, for lack of a better macro. This has the problem
of not showing you the values of the parts of the expression, making it hard to
understand what went wrong. As a workaround, some users choose to construct the
failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
is awkward especially when the expression has side-effects or is expensive to
evaluate.
Google Test gives you three different options to solve this problem:
### Using an Existing Boolean Function ###
If you already have a function or a functor that returns `bool` (or a type
that can be implicitly converted to `bool`), you can use it in a _predicate
assertion_ to get the function arguments printed for free:
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_PRED1(`_pred1, val1_`);` | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true |
| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` | _pred2(val1, val2)_ returns true |
| ... | ... | ... |
In the above, _predn_ is an _n_-ary predicate function or functor, where
_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds
if the predicate returns `true` when applied to the given arguments, and fails
otherwise. When the assertion fails, it prints the value of each argument. In
either case, the arguments are evaluated exactly once.
Here's an example. Given
```
// Returns true iff m and n have no common divisors except 1.
bool MutuallyPrime(int m, int n) { ... }
const int a = 3;
const int b = 4;
const int c = 10;
```
the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the
assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message
<pre>
!MutuallyPrime(b, c) is false, where<br>
b is 4<br>
c is 10<br>
</pre>
**Notes:**
1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this](http://code.google.com/p/googletest/wiki/V1_5_FAQ#The_compiler_complains_%22no_matching_function_to_call%22) for how to resolve it.
1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know.
_Availability_: Linux, Windows, Mac
### Using a Function That Returns an AssertionResult ###
While `EXPECT_PRED*()` and friends are handy for a quick job, the
syntax is not satisfactory: you have to use different macros for
different arities, and it feels more like Lisp than C++. The
`::testing::AssertionResult` class solves this problem.
An `AssertionResult` object represents the result of an assertion
(whether it's a success or a failure, and an associated message). You
can create an `AssertionResult` using one of these factory
functions:
```
namespace testing {
// Returns an AssertionResult object to indicate that an assertion has
// succeeded.
AssertionResult AssertionSuccess();
// Returns an AssertionResult object to indicate that an assertion has
// failed.
AssertionResult AssertionFailure();
}
```
You can then use the `<<` operator to stream messages to the
`AssertionResult` object.
To provide more readable messages in Boolean assertions
(e.g. `EXPECT_TRUE()`), write a predicate function that returns
`AssertionResult` instead of `bool`. For example, if you define
`IsEven()` as:
```
::testing::AssertionResult IsEven(int n) {
if ((n % 2) == 0)
return ::testing::AssertionSuccess();
else
return ::testing::AssertionFailure() << n << " is odd";
}
```
instead of:
```
bool IsEven(int n) {
return (n % 2) == 0;
}
```
the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print:
<pre>
Value of: !IsEven(Fib(4))<br>
Actual: false (*3 is odd*)<br>
Expected: true<br>
</pre>
instead of a more opaque
<pre>
Value of: !IsEven(Fib(4))<br>
Actual: false<br>
Expected: true<br>
</pre>
If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE`
as well, and are fine with making the predicate slower in the success
case, you can supply a success message:
```
::testing::AssertionResult IsEven(int n) {
if ((n % 2) == 0)
return ::testing::AssertionSuccess() << n << " is even";
else
return ::testing::AssertionFailure() << n << " is odd";
}
```
Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print
<pre>
Value of: !IsEven(Fib(6))<br>
Actual: true (8 is even)<br>
Expected: false<br>
</pre>
_Availability_: Linux, Windows, Mac; since version 1.4.1.
### Using a Predicate-Formatter ###
If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and
`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your
predicate do not support streaming to `ostream`, you can instead use the
following _predicate-formatter assertions_ to _fully_ customize how the
message is formatted:
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
|:--------------------|:-----------------------|:-------------|
| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);` | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`); | _pred\_format1(val1)_ is successful |