matchers.md (googletest-release-1.11.0) | : | matchers.md (googletest-release-1.12.0) | ||
---|---|---|---|---|
# Matchers Reference | # Matchers Reference | |||
A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or | A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or | |||
`EXPECT_CALL()`, or use it to validate a value directly using two macros: | `EXPECT_CALL()`, or use it to validate a value directly using two macros: | |||
| Macro | Description | | | Macro | Description | | |||
| :----------------------------------- | :------------------------------------ | | | :----------------------------------- | :------------------------------------ | | |||
| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `ma tcher`. | | | `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `ma tcher`. | | |||
| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. | | | `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. | | |||
{: .callout .note} | {: .callout .warning} | |||
**Note:** Although equality matching via `EXPECT_THAT(actual_value, | **WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)` | |||
expected_value)` is supported, prefer to make the comparison explicit via | is supported, however note that implicit conversions can cause surprising | |||
results. For example, `EXPECT_THAT(some_bool, "some string")` will compile and | ||||
may pass unintentionally. | ||||
**BEST PRACTICE:** Prefer to make the comparison explicit via | ||||
`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value, | `EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value, | |||
expected_value)`. | expected_value)`. | |||
Built-in matchers (where `argument` is the function argument, e.g. | Built-in matchers (where `argument` is the function argument, e.g. | |||
`actual_value` in the example above, or when used in the context of | `actual_value` in the example above, or when used in the context of | |||
`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are | `EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are | |||
divided into several categories. All matchers are defined in the `::testing` | divided into several categories. All matchers are defined in the `::testing` | |||
namespace unless otherwise noted. | namespace unless otherwise noted. | |||
## Wildcard | ## Wildcard | |||
skipping to change at line 91 | skipping to change at line 95 | |||
| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` va lue close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | | | `FloatNear(a_float, max_abs_error)` | `argument` is a `float` va lue close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | | |||
| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` v alue close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | | | `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` v alue close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | | |||
| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` va lue close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | | | `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` va lue close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | | |||
## String Matchers | ## String Matchers | |||
The `argument` can be either a C string or a C++ string object: | The `argument` can be either a C string or a C++ string object: | |||
| Matcher | Description | | | Matcher | Description | | |||
| :---------------------- | :------------------------------------------------- | | | :---------------------- | :------------------------------------------------- | | |||
| `ContainsRegex(string)` | `argument` matches the given regular expression. | | | `ContainsRegex(string)` | `argument` matches the given regular expression. | | |||
| `EndsWith(suffix)` | `argument` ends with string `suffix`. | | | `EndsWith(suffix)` | `argument` ends with string `suffix`. | | |||
| `HasSubstr(string)` | `argument` contains `string` as a sub-string. | | | `HasSubstr(string)` | `argument` contains `string` as a sub-string. | | |||
| `IsEmpty()` | `argument` is an empty string. | | | `IsEmpty()` | `argument` is an empty string. | | |||
| `MatchesRegex(string)` | `argument` matches the given regular expression with | | `MatchesRegex(string)` | `argument` matches the given regular expression wit | |||
the match starting at the first character and ending at the last character. | | h the match starting at the first character and ending at the last character. | | |||
| `StartsWith(prefix)` | `argument` starts with string `prefix`. | | | `StartsWith(prefix)` | `argument` starts with string `prefix`. | | |||
| `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. | | | `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. | | |||
| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. | | `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. | |||
| | | | |||
| `StrEq(string)` | `argument` is equal to `string`. | | | `StrEq(string)` | `argument` is equal to `string`. | | |||
| `StrNe(string)` | `argument` is not equal to `string`. | | | `StrNe(string)` | `argument` is not equal to `string`. | | |||
| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unesca | ||||
ped string matches `m`. | | ||||
`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They | `ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They | |||
use the regular expression syntax defined | use the regular expression syntax defined | |||
[here](../advanced.md#regular-expression-syntax). All of these matchers, except | [here](../advanced.md#regular-expression-syntax). All of these matchers, except | |||
`ContainsRegex()` and `MatchesRegex()` work for wide strings as well. | `ContainsRegex()` and `MatchesRegex()` work for wide strings as well. | |||
## Container Matchers | ## Container Matchers | |||
Most STL-style containers support `==`, so you can use `Eq(expected_container)` | Most STL-style containers support `==`, so you can use `Eq(expected_container)` | |||
or simply `expected_container` to match a container exactly. If you want to | or simply `expected_container` to match a container exactly. If you want to | |||
write the elements in-line, match them more flexibly, or get more informative | write the elements in-line, match them more flexibly, or get more informative | |||
messages, you can use: | messages, you can use: | |||
| Matcher | Description | | | Matcher | Description | | |||
| :---------------------------------------- | :------------------------------- | | | :---------------------------------------- | :------------------------------- | | |||
| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end() ` iterators are separated by a number of increments matching `m`. E.g. `BeginEnd DistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `siz e()` method, `SizeIs(m)` may be more efficient. | | | `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end() ` iterators are separated by a number of increments matching `m`. E.g. `BeginEnd DistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `siz e()` method, `SizeIs(m)` may be more efficient. | | |||
| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | | | `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | | |||
| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | | | `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | | |||
| `Contains(e).Times(n)` | `argument` contains elements that match `e`, which ca n be either a value or a matcher, and the number of matches is `n`, which can be either a value or a matcher. Unlike the plain `Contains` and `Each` this allows to check for arbitrary occurrences including testing for absence with `Contains (e).Times(0)`. | | ||||
| `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. | | | `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. | | |||
| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i *-th element matches `ei`, which can be a value or a matcher. | | | `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i *-th element matches `ei`, which can be a value or a matcher. | | |||
| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `Eleme ntsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/m atchers come from an initializer list, STL-style container, iterator range, or C -style array. | | | `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `Eleme ntsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/m atchers come from an initializer list, STL-style container, iterator range, or C -style array. | | |||
| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | | | `IsEmpty()` | `argument` is an empty container (`container.empty()`). | | |||
| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of t he expected matchers. | | | `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of t he expected matchers. | | |||
| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf( begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subs et of `argument` matches `UnorderedElementsAre(`expected matchers`)`. | | | `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf( begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subs et of `argument` matches `UnorderedElementsAre(`expected matchers`)`. | | |||
| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` cont ains the same number of elements as in `container`, and for all i, (the i-th ele ment in `argument`, the i-th element in `container`) match `m`, which is a match er on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See mo re detail below. | | | `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` cont ains the same number of elements as in `container`, and for all i, (the i-th ele ment in `argument`, the i-th element in `container`) match `m`, which is a match er on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See mo re detail below. | | |||
| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2 )` or `SizeIs(Lt(2))`. | | | `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2 )` or `SizeIs(Lt(2))`. | | |||
| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a d ifferent `i`), which can be a value or a matcher. | | | `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a d ifferent `i`), which can be a value or a matcher. | | |||
| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_c ontainer)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray( array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedEl ementsAre()` except that the expected element values/matchers come from an initi alizer list, STL-style container, iterator range, or C-style array. | | | `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_c ontainer)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray( array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedEl ementsAre()` except that the expected element values/matchers come from an initi alizer list, STL-style container, iterator range, or C-style array. | | |||
skipping to change at line 149 | skipping to change at line 155 | |||
int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)). | int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)). | |||
* The array being matched may be multi-dimensional (i.e. its elements can be | * The array being matched may be multi-dimensional (i.e. its elements can be | |||
arrays). | arrays). | |||
* `m` in `Pointwise(m, ...)` and `UnorderedPointwise(m, ...)` should be a | * `m` in `Pointwise(m, ...)` and `UnorderedPointwise(m, ...)` should be a | |||
matcher for `::std::tuple<T, U>` where `T` and `U` are the element type of | matcher for `::std::tuple<T, U>` where `T` and `U` are the element type of | |||
the actual container and the expected container, respectively. For example, | the actual container and the expected container, respectively. For example, | |||
to compare two `Foo` containers where `Foo` doesn't support `operator==`, | to compare two `Foo` containers where `Foo` doesn't support `operator==`, | |||
one might write: | one might write: | |||
```cpp | ```cpp | |||
using ::std::get; | ||||
MATCHER(FooEq, "") { | MATCHER(FooEq, "") { | |||
return std::get<0>(arg).Equals(std::get<1>(arg)); | return std::get<0>(arg).Equals(std::get<1>(arg)); | |||
} | } | |||
... | ... | |||
EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); | EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); | |||
``` | ``` | |||
## Member Matchers | ## Member Matchers | |||
| Matcher | Description | | | Matcher | Description | | |||
skipping to change at line 196 | skipping to change at line 201 | |||
* Don't use `Property()` against member functions that you do not own, because | * Don't use `Property()` against member functions that you do not own, because | |||
taking addresses of functions is fragile and generally not part of the | taking addresses of functions is fragile and generally not part of the | |||
contract of the function. | contract of the function. | |||
## Matching the Result of a Function, Functor, or Callback | ## Matching the Result of a Function, Functor, or Callback | |||
| Matcher | Description | | | Matcher | Description | | |||
| :--------------- | :------------------------------------------------ | | | :--------------- | :------------------------------------------------ | | |||
| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. | | | `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. | | |||
| `ResultOf(result_description, f, m)` | The same as the two-parameter version, but provides a better error message. | ||||
## Pointer Matchers | ## Pointer Matchers | |||
| Matcher | Description | | | Matcher | Description | | |||
| :------------------------ | :---------------------------------------------- | | | :------------------------ | :---------------------------------------------- | | |||
| `Address(m)` | the result of `std::addressof(argument)` matches ` m`. | | | `Address(m)` | the result of `std::addressof(argument)` matches ` m`. | | |||
| `Pointee(m)` | `argument` (either a smart pointer or a raw pointe r) points to a value that matches matcher `m`. | | | `Pointee(m)` | `argument` (either a smart pointer or a raw pointe r) points to a value that matches matcher `m`. | | |||
| `Pointer(m)` | `argument` (either a smart pointer or a raw pointe r) contains a pointer that matches `m`. `m` will match against the raw pointer r egardless of the type of `argument`. | | | `Pointer(m)` | `argument` (either a smart pointer or a raw pointe r) contains a pointer that matches `m`. `m` will match against the raw pointer r egardless of the type of `argument`. | | |||
| `WhenDynamicCastTo<T>(m)` | when `argument` is passed through `dynamic_cast<T> ()`, it matches matcher `m`. | | | `WhenDynamicCastTo<T>(m)` | when `argument` is passed through `dynamic_cast<T> ()`, it matches matcher `m`. | | |||
skipping to change at line 240 | skipping to change at line 246 | |||
You can make a matcher from one or more other matchers: | You can make a matcher from one or more other matchers: | |||
| Matcher | Description | | | Matcher | Description | | |||
| :------------------------------- | :-------------------------------------- | | | :------------------------------- | :-------------------------------------- | | |||
| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn` . | | | `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn` . | | |||
| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf( )` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | | | `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf( )` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | | |||
| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1 ` to `mn`. | | | `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1 ` to `mn`. | | |||
| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf( )` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | | | `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf( )` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | | |||
| `Not(m)` | `argument` doesn't match matcher `m`. | | | `Not(m)` | `argument` doesn't match matcher `m`. | | |||
| `Conditional(cond, m1, m2)` | Matches matcher `m1` if `cond` evaluates to true , else matches `m2`.| | ||||
## Adapters for Matchers | ## Adapters for Matchers | |||
| Matcher | Description | | | Matcher | Description | | |||
| :---------------------- | :------------------------------------ | | | :---------------------- | :------------------------------------ | | |||
| `MatcherCast<T>(m)` | casts matcher `m` to type `Matcher<T>`. | | | `MatcherCast<T>(m)` | casts matcher `m` to type `Matcher<T>`. | | |||
| `SafeMatcherCast<T>(m)` | [safely casts](../gmock_cook_book.md#SafeMatcherCast ) matcher `m` to type `Matcher<T>`. | | | `SafeMatcherCast<T>(m)` | [safely casts](../gmock_cook_book.md#SafeMatcherCast ) matcher `m` to type `Matcher<T>`. | | |||
| `Truly(predicate)` | `predicate(argument)` returns something considered b y C++ to be true, where `predicate` is a function or functor. | | | `Truly(predicate)` | `predicate(argument)` returns something considered b y C++ to be true, where `predicate` is a function or functor. | | |||
`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`, | `AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`, | |||
skipping to change at line 262 | skipping to change at line 269 | |||
## Using Matchers as Predicates {#MatchersAsPredicatesCheat} | ## Using Matchers as Predicates {#MatchersAsPredicatesCheat} | |||
| Matcher | Description | | | Matcher | Description | | |||
| :---------------------------- | :------------------------------------------ | | | :---------------------------- | :------------------------------------------ | | |||
| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. | | | `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. | | |||
| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `valu e` matches `m`, explaining the result to `result_listener`. | | | `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `valu e` matches `m`, explaining the result to `result_listener`. | | |||
| `Value(value, m)` | evaluates to `true` if `value` matches `m`. | | | `Value(value, m)` | evaluates to `true` if `value` matches `m`. | | |||
## Defining Matchers | ## Defining Matchers | |||
| Matcher | Description | | | Macro | Description | | |||
| :----------------------------------- | :------------------------------------ | | | :----------------------------------- | :------------------------------------ | | |||
| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven() ` to match an even number. | | | `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven() ` to match an even number. | | |||
| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n) ` to match a number divisible by `n`. | | | `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n) ` to match a number divisible by `n`. | | |||
| `MATCHER_P2(IsBetween, a, b, absl::StrCat(negation ? "isn't" : "is", " between ", PrintToString(a), " and ", PrintToString(b))) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b `]. | | | `MATCHER_P2(IsBetween, a, b, absl::StrCat(negation ? "isn't" : "is", " between ", PrintToString(a), " and ", PrintToString(b))) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b `]. | | |||
**Notes:** | **Notes:** | |||
1. The `MATCHER*` macros cannot be used inside a function or class. | 1. The `MATCHER*` macros cannot be used inside a function or class. | |||
2. The matcher body must be *purely functional* (i.e. it cannot have any side | 2. The matcher body must be *purely functional* (i.e. it cannot have any side | |||
effect, and the result must not depend on anything other than the value | effect, and the result must not depend on anything other than the value | |||
End of changes. 7 change blocks. | ||||
17 lines changed or deleted | 25 lines changed or added |