Commit d5d6ff94 by Abseil Team Committed by Andy Soffer

Googletest export

Create Assertions Reference PiperOrigin-RevId: 375824718
parent 8ceecc27
...@@ -21,6 +21,8 @@ nav: ...@@ -21,6 +21,8 @@ nav:
url: "/gmock_cheat_sheet.html" url: "/gmock_cheat_sheet.html"
- section: "References" - section: "References"
items: items:
- title: "Assertions"
url: "/reference/assertions.html"
- title: "Matchers" - title: "Matchers"
url: "/reference/matchers.html" url: "/reference/matchers.html"
- title: "Actions" - title: "Actions"
......
...@@ -279,8 +279,9 @@ disabled by our build system. Please see more details ...@@ -279,8 +279,9 @@ disabled by our build system. Please see more details
## My death test hangs (or seg-faults). How do I fix it? ## My death test hangs (or seg-faults). How do I fix it?
In googletest, death tests are run in a child process and the way they work is In googletest, death tests are run in a child process and the way they work is
delicate. To write death tests you really need to understand how they work. delicate. To write death tests you really need to understand how they work—see
Please make sure you have read [this](advanced.md#how-it-works). the details at [Death Assertions](reference/assertions.md#death) in the
Assertions Reference.
In particular, death tests don't like having multiple threads in the parent In particular, death tests don't like having multiple threads in the parent
process. So the first thing you can try is to eliminate creating threads outside process. So the first thing you can try is to eliminate creating threads outside
...@@ -353,72 +354,8 @@ You may still want to use `SetUp()/TearDown()` in the following cases: ...@@ -353,72 +354,8 @@ You may still want to use `SetUp()/TearDown()` in the following cases:
## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it? ## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it?
If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the
overloaded or a template, the compiler will have trouble figuring out which Assertions Reference.
overloaded version it should use. `ASSERT_PRED_FORMAT*` and
`EXPECT_PRED_FORMAT*` don't have this problem.
If you see this error, you might want to switch to
`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
message. If, however, that is not an option, you can resolve the problem by
explicitly telling the compiler which version to pick.
For example, suppose you have
```c++
bool IsPositive(int n) {
return n > 0;
}
bool IsPositive(double x) {
return x > 0;
}
```
you will get a compiler error if you write
```c++
EXPECT_PRED1(IsPositive, 5);
```
However, this will work:
```c++
EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
```
(The stuff inside the angled brackets for the `static_cast` operator is the type
of the function pointer for the `int`-version of `IsPositive()`.)
As another example, when you have a template function
```c++
template <typename T>
bool IsNegative(T x) {
return x < 0;
}
```
you can use it in a predicate assertion like this:
```c++
ASSERT_PRED1(IsNegative<int>, -5);
```
Things are more interesting if your template has more than one parameter. The
following won't compile:
```c++
ASSERT_PRED2(GreaterThan<int, int>, 5, 0);
```
as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which
is one more than expected. The workaround is to wrap the predicate function in
parentheses:
```c++
ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
```
## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why? ## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why?
......
...@@ -1137,51 +1137,8 @@ Matches(AllOf(Ge(0), Le(100), Ne(50))) ...@@ -1137,51 +1137,8 @@ Matches(AllOf(Ge(0), Le(100), Ne(50)))
### Using Matchers in googletest Assertions ### Using Matchers in googletest Assertions
Since matchers are basically predicates that also know how to describe See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions
themselves, there is a way to take advantage of them in googletest assertions. Reference.
It's called `ASSERT_THAT` and `EXPECT_THAT`:
```cpp
ASSERT_THAT(value, matcher); // Asserts that value matches matcher.
EXPECT_THAT(value, matcher); // The non-fatal version.
```
For example, in a googletest test you can write:
```cpp
#include "gmock/gmock.h"
using ::testing::AllOf;
using ::testing::Ge;
using ::testing::Le;
using ::testing::MatchesRegex;
using ::testing::StartsWith;
...
EXPECT_THAT(Foo(), StartsWith("Hello"));
EXPECT_THAT(Bar(), MatchesRegex("Line \\d+"));
ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10)));
```
which (as you can probably guess) executes `Foo()`, `Bar()`, and `Baz()`, and
verifies that:
* `Foo()` returns a string that starts with `"Hello"`.
* `Bar()` returns a string that matches regular expression `"Line \\d+"`.
* `Baz()` returns a number in the range [5, 10].
The nice thing about these macros is that *they read like English*. They
generate informative messages too. For example, if the first `EXPECT_THAT()`
above fails, the message will be something like:
```cpp
Value of: Foo()
Actual: "Hi, world!"
Expected: starts with "Hello"
```
**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was borrowed from Joe Walnes'
Hamcrest project, which adds `assertThat()` to JUnit.
### Using Predicates as Matchers ### Using Predicates as Matchers
......
...@@ -118,7 +118,10 @@ Depending on the nature of the leak, it may or may not be worth fixing - so keep ...@@ -118,7 +118,10 @@ Depending on the nature of the leak, it may or may not be worth fixing - so keep
this in mind if you get a heap checker error in addition to assertion errors. this in mind if you get a heap checker error in addition to assertion errors.
To provide a custom failure message, simply stream it into the macro using the To provide a custom failure message, simply stream it into the macro using the
`<<` operator or a sequence of such operators. An example: `<<` operator or a sequence of such operators. See the following example, using
the
[`ASSERT_EQ` and `EXPECT_EQ`](reference/assertions.md?cl=374325853#EXPECT_EQ)
macros to verify value equality:
```c++ ```c++
ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
...@@ -133,110 +136,12 @@ macro--in particular, C strings and `string` objects. If a wide string ...@@ -133,110 +136,12 @@ macro--in particular, C strings and `string` objects. If a wide string
(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is (`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
streamed to an assertion, it will be translated to UTF-8 when printed. streamed to an assertion, it will be translated to UTF-8 when printed.
### Basic Assertions GoogleTest provides a collection of assertions for verifying the behavior of
your code in various ways. You can check Boolean conditions, compare values
These assertions do basic true/false condition testing. based on relational operators, verify string values, floating-point values, and
much more. There are even assertions that enable you to verify more complex
Fatal assertion | Nonfatal assertion | Verifies states by providing custom predicates. For the complete list of assertions
-------------------------- | -------------------------- | -------------------- provided by GoogleTest, see the [Assertions Reference](reference/assertions.md).
`ASSERT_TRUE(condition);` | `EXPECT_TRUE(condition);` | `condition` is true
`ASSERT_FALSE(condition);` | `EXPECT_FALSE(condition);` | `condition` is false
Remember, when they fail, `ASSERT_*` yields a fatal failure and returns from the
current function, while `EXPECT_*` yields a nonfatal failure, allowing the
function to continue running. In either case, an assertion failure means its
containing test fails.
**Availability**: Linux, Windows, Mac.
### Binary Comparison
This section describes assertions that compare two values.
Fatal assertion | Nonfatal assertion | Verifies
------------------------ | ------------------------ | --------------
`ASSERT_EQ(val1, val2);` | `EXPECT_EQ(val1, val2);` | `val1 == val2`
`ASSERT_NE(val1, val2);` | `EXPECT_NE(val1, val2);` | `val1 != val2`
`ASSERT_LT(val1, val2);` | `EXPECT_LT(val1, val2);` | `val1 < val2`
`ASSERT_LE(val1, val2);` | `EXPECT_LE(val1, val2);` | `val1 <= val2`
`ASSERT_GT(val1, val2);` | `EXPECT_GT(val1, val2);` | `val1 > val2`
`ASSERT_GE(val1, val2);` | `EXPECT_GE(val1, val2);` | `val1 >= val2`
Value arguments must be comparable by the assertion's comparison operator or
you'll get a compiler error. We used to require the arguments to support the
`<<` operator for streaming to an `ostream`, but this is no longer necessary. If
`<<` is supported, it will be called to print the arguments when the assertion
fails; otherwise googletest will attempt to print them in the best way it can.
For more details and how to customize the printing of the arguments, see the
[documentation](./advanced.md#teaching-googletest-how-to-print-your-values).
These assertions can work with a user-defined type, but only if you define the
corresponding comparison operator (e.g., `==` or `<`). Since this is discouraged
by the Google
[C++ Style Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading),
you may need to use `ASSERT_TRUE()` or `EXPECT_TRUE()` to assert the equality of
two objects of a user-defined type.
However, when possible, `ASSERT_EQ(actual, expected)` is preferred to
`ASSERT_TRUE(actual == expected)`, since it tells you `actual` and `expected`'s
values on failure.
Arguments are always evaluated exactly once. Therefore, it's OK for the
arguments to have side effects. However, as with any ordinary C/C++ function,
the arguments' evaluation order is undefined (i.e., the compiler is free to
choose any order), and your code should not depend on any particular argument
evaluation order.
`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
tests if they are in the same memory location, not if they have the same value.
Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
`ASSERT_STREQ()`, which will be described later on. In particular, to assert
that a C string is `NULL`, use `ASSERT_STREQ(c_string, NULL)`. Consider using
`ASSERT_EQ(c_string, nullptr)` if c++11 is supported. To compare two `string`
objects, you should use `ASSERT_EQ`.
When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)`
instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is
typed, while `NULL` is not. See the [FAQ](faq.md) for more details.
If you're working with floating point numbers, you may want to use the floating
point variations of some of these macros in order to avoid problems caused by
rounding. See [Advanced googletest Topics](advanced.md) for details.
Macros in this section work with both narrow and wide string objects (`string`
and `wstring`).
**Availability**: Linux, Windows, Mac.
**Historical note**: Before February 2016 `*_EQ` had a convention of calling it
as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now
`*_EQ` treats both parameters in the same way.
### String Comparison
The assertions in this group compare two **C strings**. If you want to compare
two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
| Fatal assertion | Nonfatal assertion | Verifies |
| -------------------------- | ------------------------------ | -------------------------------------------------------- |
| `ASSERT_STREQ(str1,str2);` | `EXPECT_STREQ(str1,str2);` | the two C strings have the same content |
| `ASSERT_STRNE(str1,str2);` | `EXPECT_STRNE(str1,str2);` | the two C strings have different contents |
| `ASSERT_STRCASEEQ(str1,str2);` | `EXPECT_STRCASEEQ(str1,str2);` | the two C strings have the same content, ignoring case |
| `ASSERT_STRCASENE(str1,str2);` | `EXPECT_STRCASENE(str1,str2);` | the two C strings have different contents, ignoring case |
Note that "CASE" in an assertion name means that case is ignored. A `NULL`
pointer and an empty string are considered *different*.
`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a comparison
of two wide strings fails, their values will be printed as UTF-8 narrow strings.
**Availability**: Linux, Windows, Mac.
**See also**: For more string comparison tricks (substring, prefix, suffix, and
regular expression matching, for example), see [this](advanced.md) in the
Advanced googletest Guide.
## Simple Tests ## Simple Tests
......
...@@ -56,7 +56,7 @@ will be changed. ...@@ -56,7 +56,7 @@ will be changed.
`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types `IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types
that can be explicitly converted to Boolean, but are not implicitly converted to that can be explicitly converted to Boolean, but are not implicitly converted to
Boolean. In other cases, you can use the basic Boolean. In other cases, you can use the basic
[`EXPECT_TRUE` and `EXPECT_FALSE`](../primer.md#basic-assertions) assertions. [`EXPECT_TRUE` and `EXPECT_FALSE`](assertions.md#boolean) assertions.
## Floating-Point Matchers {#FpMatchers} ## Floating-Point Matchers {#FpMatchers}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment