|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. |
|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. |
## Generic Comparison ##
## Generic Comparison ##
|`Eq(value)` or `value`|`argument == value`|
| Matcher | Description |
|:---------------------|:------------------|
|:---------------------|:------------------|
|`Eq(value)` or `value`|`argument == value`|
|`Ge(value)` |`argument >= value`|
|`Ge(value)` |`argument >= value`|
|`Gt(value)` |`argument > value` |
|`Gt(value)` |`argument > value` |
|`Le(value)` |`argument <= value`|
|`Le(value)` |`argument <= value`|
...
@@ -178,8 +181,7 @@ divided into several categories:
...
@@ -178,8 +181,7 @@ divided into several categories:
|`Ne(value)` |`argument != value`|
|`Ne(value)` |`argument != value`|
|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).|
|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).|
|`NotNull()` |`argument` is a non-null pointer (raw or smart).|
|`NotNull()` |`argument` is a non-null pointer (raw or smart).|
|`VariantWith<T>(m)` |`argument` is `variant<>` that holds the alternative of
|`VariantWith<T>(m)` |`argument` is `variant<>` that holds the alternative of type T with a value matching `m`.|
type T with a value matching `m`.|
|`Ref(variable)` |`argument` is a reference to `variable`.|
|`Ref(variable)` |`argument` is a reference to `variable`.|
|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.|
|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.|
...
@@ -192,11 +194,12 @@ matcher will be changed.
...
@@ -192,11 +194,12 @@ matcher will be changed.
## Floating-Point Matchers ##
## Floating-Point Matchers ##
|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.|
|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. |
|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. |
|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. |
|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. |
|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. |
|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. |
|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. |
The above matchers use ULP-based comparison (the same as used in
The above matchers use ULP-based comparison (the same as used in
[Google Test](../../googletest/)). They
[Google Test](../../googletest/)). They
...
@@ -206,26 +209,28 @@ the IEEE standard, which requires comparing two NaNs for equality to
...
@@ -206,26 +209,28 @@ the IEEE standard, which requires comparing two NaNs for equality to
return false. The `NanSensitive*` version instead treats two NaNs as
return false. The `NanSensitive*` version instead treats two NaNs as
equal, which is often what a user wants.
equal, which is often what a user wants.
| Matcher | Description |
|:--------|:------------|
|`DoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal.|
|`DoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal.|
|`FloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal.|
|`FloatNear(a_float, max_abs_error)` |`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |
|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal.|
|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. |
|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal.|
|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value 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:
|`ContainsRegex(string)`|`argument` matches the given regular expression.|
|`EndsWith(suffix)` |`argument` ends with string `suffix`. |
|`ContainsRegex(string)`|`argument` matches the given regular expression. |
|`HasSubstr(string)` |`argument` contains `string` as a sub-string. |
|`EndsWith(suffix)` |`argument` ends with string `suffix`. |
|`HasSubstr(string)` |`argument` contains `string` as a sub-string. |
|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.|
|`MatchesRegex(string)` |`argument` matches the given regular expression with 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`. |
`ContainsRegex()` and `MatchesRegex()` use the regular expression
`ContainsRegex()` and `MatchesRegex()` use the regular expression
syntax defined
syntax defined
...
@@ -240,18 +245,19 @@ Most STL-style containers support `==`, so you can use
...
@@ -240,18 +245,19 @@ Most STL-style containers support `==`, so you can use
container exactly. If you want to write the elements in-line,
container exactly. If you want to write the elements in-line,
match them more flexibly, or get more informative messages, you can use:
match them more flexibly, or get more informative messages, you can use:
| Matcher | Description |
|:--------|:------------|
| `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. |
| `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. 0 to 10 arguments are allowed. |
| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. |
| `ElementsAreArray({ e0, e1, ..., en })`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. |
| `ElementsAreArray({ e0, e1, ..., en })`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. |
| `IsEmpty()` | `argument` is an empty container (`container.empty()`). |
| `IsEmpty()`| `argument` is an empty container (`container.empty()`). |
| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher 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 more detail below. |
| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher 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 more 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 each element matches an `ei` (for a different `i`), which can be a value or a matcher. 0 to 10 arguments are allowed. |
| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under some permutation each element matches an `ei` (for a different `i`), which can be a value or a matcher. 0 to 10 arguments are allowed. |
| `UnorderedElementsAreArray({ e0, e1, ..., en })`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. |
| `UnorderedElementsAreArray({ e0, e1, ..., en })`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. |
| `WhenSorted(m)`| When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. |
| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. |
| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater<int>(), ElementsAre(3, 2, 1))`. |
| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater<int>(), ElementsAre(3, 2, 1))`. |
Notes:
Notes:
...
@@ -262,7 +268,7 @@ Notes:
...
@@ -262,7 +268,7 @@ Notes:
* The array being matched may be multi-dimensional (i.e. its elements can be arrays).
* The array being matched may be multi-dimensional (i.e. its elements can be arrays).
*`m` in `Pointwise(m, ...)` should be a matcher for `::testing::tuple<T, U>` where `T` and `U` are the element type of the actual container and the expected container, respectively. For example, to compare two `Foo` containers where `Foo` doesn't support `operator==` but has an `Equals()` method, one might write:
*`m` in `Pointwise(m, ...)` should be a matcher for `::testing::tuple<T, U>` where `T` and `U` are the element type of the actual container and the expected container, respectively. For example, to compare two `Foo` containers where `Foo` doesn't support `operator==` but has an `Equals()` method, one might write:
|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
|`Key(e)`|`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.|
|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.|
|`Pair(m1, m2)`|`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`.|
|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. |
|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
## Matching the Result of a Function or Functor ##
## Matching the Result of a Function or Functor ##
|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.|
| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `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 macher `IsDivisibleBy(n)` to match a number divisible by `n`. |
| `MATCHER_P2(IsBetween, a, b, std::string(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, std::string(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`]. |
...
@@ -349,9 +364,10 @@ You can make a matcher from one or more other matchers:
...
@@ -349,9 +364,10 @@ You can make a matcher from one or more other matchers:
## Matchers as Test Assertions ##
## Matchers as Test Assertions ##
| Matcher | Description |
|:--------|:------------|
|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](../../googletest/docs/primer.md#assertions) if the value of `expression` doesn't match matcher `m`.|
|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](../../googletest/docs/primer.md#assertions) if the value of `expression` doesn't match matcher `m`.|
|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`.|
|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. |
# Actions #
# Actions #
...
@@ -359,77 +375,83 @@ You can make a matcher from one or more other matchers:
...
@@ -359,77 +375,83 @@ You can make a matcher from one or more other matchers:
## Returning a Value ##
## Returning a Value ##
| Matcher | Description |
|:--------|:------------|
|`Return()`|Return from a `void` mock function.|
|`Return()`|Return from a `void` mock function.|
|:---------|:----------------------------------|
|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.|
|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.|
|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.|
|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.|
|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.|
|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.|
|`ReturnNull()`|Return a null pointer.|
|`ReturnNull()`|Return a null pointer.|
|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.|
|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.|
|`ReturnRef(variable)`|Return a reference to `variable`.|
|`ReturnRef(variable)`|Return a reference to `variable`.|
|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.|
|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.|
## Side Effects ##
## Side Effects ##
| Matcher | Description |
|:--------|:------------|
|`Assign(&variable, value)`|Assign `value` to variable.|
|`Assign(&variable, value)`|Assign `value` to variable.|
|`DeleteArg<N>()`| Delete the `N`-th (0-based) argument, which must be a pointer.|
| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. |
|`SaveArg<N>(pointer)`| Save the `N`-th (0-based) argument to `*pointer`.|
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. |
|`SaveArgPointee<N>(pointer)`| Save the value pointed to by the `N`-th (0-based) argument to `*pointer`.|
| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
|`SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. |
| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. |
|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.|
|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.|
|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.|
|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.|
|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.|
|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.|
|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.|
|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.|
|`Throw(exception)`|Throws the given exception, which can be any copyable value. Available since v1.1.0.|
|`Throw(exception)`|Throws the given exception, which can be any copyable value. Available since v1.1.0.|
## Using a Function or a Functor as an Action ##
## Using a Function or a Functor as an Action ##
| Matcher | Description |
|:--------|:------------|
|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.|
|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.|
|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function.|
|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. |
|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments.|
|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. |
|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments.|
|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. |
|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.|
|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.|
The return value of the invoked function is used as the return value
The return value of the invoked function is used as the return value
of the action.
of the action.
When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`:
When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`:
**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error.
**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error.
## Composite Actions ##
## Composite Actions ##
|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. |
|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. |
|`DoAll(a1, a2, ..., an)` |Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. |
|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. |
|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. |
|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. |
|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. |
|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. |
|`WithoutArgs(a)` |Perform action `a` without any arguments. |
|`WithoutArgs(a)`|Perform action `a` without any arguments. |
## Defining Actions ##
## Defining Actions ##
| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
@@ -1334,7 +1334,7 @@ The sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have
...
@@ -1334,7 +1334,7 @@ The sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have
So how do we tell Google Mock that `GetDomainOwner()` can be called with some other arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`:
So how do we tell Google Mock that `GetDomainOwner()` can be called with some other arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`:
```
```cpp
EXPECT_CALL(mock_registry,GetDomainOwner(_))
EXPECT_CALL(mock_registry,GetDomainOwner(_))
.Times(AnyNumber());// catches all other calls to this method.
.Times(AnyNumber());// catches all other calls to this method.
@@ -1360,7 +1360,7 @@ If you would rather have all calls occur in the order of the
...
@@ -1360,7 +1360,7 @@ If you would rather have all calls occur in the order of the
expectations, put the `EXPECT_CALL()` statements in a block where you
expectations, put the `EXPECT_CALL()` statements in a block where you
define a variable of type `InSequence`:
define a variable of type `InSequence`:
```
```cpp
using::testing::_;
using::testing::_;
using::testing::InSequence;
using::testing::InSequence;
...
@@ -1411,7 +1411,7 @@ things: first to define some `Sequence` objects, and then for each
...
@@ -1411,7 +1411,7 @@ things: first to define some `Sequence` objects, and then for each
of. Expectations in the same sequence must occur in the order they are
of. Expectations in the same sequence must occur in the order they are
written. For example,
written. For example,
```
```cpp
using::testing::Sequence;
using::testing::Sequence;
Sequences1,s2;
Sequences1,s2;
...
@@ -1447,7 +1447,7 @@ that are still active. An expectation is active when created, and
...
@@ -1447,7 +1447,7 @@ that are still active. An expectation is active when created, and
becomes inactive (aka _retires_) when a call that has to occur later
becomes inactive (aka _retires_) when a call that has to occur later
has occurred. For example, in
has occurred. For example, in
```
```cpp
using::testing::_;
using::testing::_;
using::testing::Sequence;
using::testing::Sequence;
...
@@ -1468,7 +1468,7 @@ as soon as either #2 or #3 is matched, #1 will retire. If a warning
...
@@ -1468,7 +1468,7 @@ as soon as either #2 or #3 is matched, #1 will retire. If a warning
Note that an expectation doesn't retire automatically when it's
Note that an expectation doesn't retire automatically when it's
saturated. For example,
saturated. For example,
```
```cpp
using::testing::_;
using::testing::_;
...
...
EXPECT_CALL(log,Log(WARNING,_,_));// #1
EXPECT_CALL(log,Log(WARNING,_,_));// #1
...
@@ -1482,7 +1482,7 @@ match again and result in an upper-bound-violated error.
...
@@ -1482,7 +1482,7 @@ match again and result in an upper-bound-violated error.
If this is not what you want, you can ask an expectation to retire as
If this is not what you want, you can ask an expectation to retire as
soon as it becomes saturated:
soon as it becomes saturated:
```
```cpp
using::testing::_;
using::testing::_;
...
...
EXPECT_CALL(log,Log(WARNING,_,_));// #1
EXPECT_CALL(log,Log(WARNING,_,_));// #1
...
@@ -1501,7 +1501,7 @@ will match #1 - there will be no error.
...
@@ -1501,7 +1501,7 @@ will match #1 - there will be no error.
If a mock function's return type is a reference, you need to use
If a mock function's return type is a reference, you need to use
`ReturnRef()` instead of `Return()` to return a result:
`ReturnRef()` instead of `Return()` to return a result:
```
```cpp
using::testing::ReturnRef;
using::testing::ReturnRef;
classMockFoo:publicFoo{
classMockFoo:publicFoo{
...
@@ -1531,7 +1531,7 @@ as doing that usually indicates a user error. So, what shall you do?
...
@@ -1531,7 +1531,7 @@ as doing that usually indicates a user error. So, what shall you do?
You may be tempted to try `ByRef()`:
You may be tempted to try `ByRef()`:
```
```cpp
usingtesting::ByRef;
usingtesting::ByRef;
usingtesting::Return;
usingtesting::Return;
...
@@ -1568,7 +1568,7 @@ and `Return(ByRef(x))` will always return 0.
...
@@ -1568,7 +1568,7 @@ and `Return(ByRef(x))` will always return 0.
specifically. It returns the value pointed to by `pointer` at the time
specifically. It returns the value pointed to by `pointer` at the time
the action is _executed_:
the action is _executed_:
```
```cpp
usingtesting::ReturnPointee;
usingtesting::ReturnPointee;
...
...
intx=0;
intx=0;
...
@@ -1585,7 +1585,7 @@ Want to do more than one thing when a function is called? That's
...
@@ -1585,7 +1585,7 @@ Want to do more than one thing when a function is called? That's
fine. `DoAll()` allow you to do sequence of actions every time. Only
fine. `DoAll()` allow you to do sequence of actions every time. Only
the return value of the last action in the sequence will be used.
the return value of the last action in the sequence will be used.
```
```cpp
using::testing::DoAll;
using::testing::DoAll;
classMockFoo:publicFoo{
classMockFoo:publicFoo{
...
@@ -1611,7 +1611,7 @@ define your own action by implementing `::testing::ActionInterface`.
...
@@ -1611,7 +1611,7 @@ define your own action by implementing `::testing::ActionInterface`.
If all you need to do is to change an output argument, the built-in
If all you need to do is to change an output argument, the built-in
`SetArgPointee()` action is convenient:
`SetArgPointee()` action is convenient:
```
```cpp
using::testing::SetArgPointee;
using::testing::SetArgPointee;
classMockMutator:publicMutator{
classMockMutator:publicMutator{
...
@@ -1638,7 +1638,7 @@ constructor and assignment operator.
...
@@ -1638,7 +1638,7 @@ constructor and assignment operator.
If the mock method also needs to return a value as well, you can chain
If the mock method also needs to return a value as well, you can chain
`SetArgPointee()` with `Return()` using `DoAll()`:
`SetArgPointee()` with `Return()` using `DoAll()`:
```
```cpp
using::testing::_;
using::testing::_;
using::testing::Return;
using::testing::Return;
using::testing::SetArgPointee;
using::testing::SetArgPointee;
...
@@ -1661,7 +1661,7 @@ If the output argument is an array, use the
...
@@ -1661,7 +1661,7 @@ If the output argument is an array, use the
elements in source range `[first, last)` to the array pointed to by
elements in source range `[first, last)` to the array pointed to by
the `N`-th (0-based) argument:
the `N`-th (0-based) argument:
```
```cpp
using::testing::NotNull;
using::testing::NotNull;
using::testing::SetArrayArgument;
using::testing::SetArrayArgument;
...
@@ -1680,7 +1680,7 @@ class MockArrayMutator : public ArrayMutator {
...
@@ -1680,7 +1680,7 @@ class MockArrayMutator : public ArrayMutator {
This also works when the argument is an output iterator:
This also works when the argument is an output iterator:
```
```cpp
using::testing::_;
using::testing::_;
using::testing::SetArrayArgument;
using::testing::SetArrayArgument;
...
@@ -1704,7 +1704,7 @@ class MockRolodex : public Rolodex {
...
@@ -1704,7 +1704,7 @@ class MockRolodex : public Rolodex {
If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call:
If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call:
```
```cpp
using::testing::InSequence;
using::testing::InSequence;
using::testing::Return;
using::testing::Return;
...
@@ -1724,7 +1724,7 @@ This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called
...
@@ -1724,7 +1724,7 @@ This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called
If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable:
If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable:
```
```cpp
using::testing::_;
using::testing::_;
using::testing::SaveArg;
using::testing::SaveArg;
using::testing::Return;
using::testing::Return;
...
@@ -1754,7 +1754,7 @@ to specify a default value for types Google Mock doesn't know
...
@@ -1754,7 +1754,7 @@ to specify a default value for types Google Mock doesn't know
about. You can do this using the `::testing::DefaultValue` class
about. You can do this using the `::testing::DefaultValue` class
template:
template:
```
```cpp
classMockFoo:publicFoo{
classMockFoo:publicFoo{
public:
public:
MOCK_METHOD0(CalculateBar,Bar());
MOCK_METHOD0(CalculateBar,Bar());
...
@@ -1790,7 +1790,7 @@ have two mock methods with the same return type and you want them to
...
@@ -1790,7 +1790,7 @@ have two mock methods with the same return type and you want them to
have different behaviors. The `ON_CALL()` macro allows you to
have different behaviors. The `ON_CALL()` macro allows you to
customize your mock's behavior at the method level:
customize your mock's behavior at the method level:
```
```cpp
using::testing::_;
using::testing::_;
using::testing::AnyNumber;
using::testing::AnyNumber;
using::testing::Gt;
using::testing::Gt;
...
@@ -1823,7 +1823,7 @@ specialize the mock's behavior later.
...
@@ -1823,7 +1823,7 @@ specialize the mock's behavior later.
If the built-in actions don't suit you, you can easily use an existing
If the built-in actions don't suit you, you can easily use an existing
function, method, or functor as an action:
function, method, or functor as an action:
```
```cpp
using::testing::_;
using::testing::_;
using::testing::Invoke;
using::testing::Invoke;
...
@@ -1878,7 +1878,7 @@ tedious and obscures the intent of the test.
...
@@ -1878,7 +1878,7 @@ tedious and obscures the intent of the test.
that it doesn't pass the mock function's arguments to the
that it doesn't pass the mock function's arguments to the
callee. Here's an example:
callee. Here's an example:
```
```cpp
using::testing::_;
using::testing::_;
using::testing::InvokeWithoutArgs;
using::testing::InvokeWithoutArgs;
...
@@ -1902,7 +1902,7 @@ bool Job1() { ... }
...
@@ -1902,7 +1902,7 @@ bool Job1() { ... }
Sometimes a mock function will receive a function pointer or a functor
Sometimes a mock function will receive a function pointer or a functor
(in other words, a "callable") as an argument, e.g.
(in other words, a "callable") as an argument, e.g.
```
```cpp
classMockFoo:publicFoo{
classMockFoo:publicFoo{
public:
public:
MOCK_METHOD2(DoThis,bool(intn,bool(*fp)(int)));
MOCK_METHOD2(DoThis,bool(intn,bool(*fp)(int)));
...
@@ -1911,7 +1911,7 @@ class MockFoo : public Foo {
...
@@ -1911,7 +1911,7 @@ class MockFoo : public Foo {
and you may want to invoke this callable argument:
and you may want to invoke this callable argument:
```
```cpp
using::testing::_;
using::testing::_;
...
...
MockFoofoo;
MockFoofoo;
...
@@ -1927,7 +1927,7 @@ Or do you really?
...
@@ -1927,7 +1927,7 @@ Or do you really?
Well, Google Mock has an action to solve _exactly_ this problem:
Well, Google Mock has an action to solve _exactly_ this problem:
```
```cpp
InvokeArgument<N>(arg_1,arg_2,...,arg_m)
InvokeArgument<N>(arg_1,arg_2,...,arg_m)
```
```
...
@@ -1937,7 +1937,7 @@ a function pointer or a functor, Google Mock handles them both.
...
@@ -1937,7 +1937,7 @@ a function pointer or a functor, Google Mock handles them both.
With that, you could write:
With that, you could write:
```
```cpp
using::testing::_;
using::testing::_;
using::testing::InvokeArgument;
using::testing::InvokeArgument;
...
...
...
@@ -1950,7 +1950,7 @@ using ::testing::InvokeArgument;
...
@@ -1950,7 +1950,7 @@ using ::testing::InvokeArgument;
What if the callable takes an argument by reference? No problem - just
What if the callable takes an argument by reference? No problem - just
@@ -49,7 +49,7 @@ Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/
...
@@ -49,7 +49,7 @@ Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/
# A Case for Mock Turtles #
# A Case for Mock Turtles #
Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface:
Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface:
```
```cpp
classTurtle{
classTurtle{
...
...
virtual~Turtle(){}
virtual~Turtle(){}
...
@@ -83,7 +83,7 @@ Using the `Turtle` interface as example, here are the simple steps you need to f
...
@@ -83,7 +83,7 @@ Using the `Turtle` interface as example, here are the simple steps you need to f
After the process, you should have something like:
After the process, you should have something like:
```
```cpp
#include "gmock/gmock.h" // Brings in Google Mock.
#include "gmock/gmock.h" // Brings in Google Mock.
classMockTurtle:publicTurtle{
classMockTurtle:publicTurtle{
public:
public:
...
@@ -125,7 +125,7 @@ Once you have a mock class, using it is easy. The typical work flow is:
...
@@ -125,7 +125,7 @@ Once you have a mock class, using it is easy. The typical work flow is:
Here's an example:
Here's an example:
```
```cpp
#include "path/to/mock-turtle.h"
#include "path/to/mock-turtle.h"
#include "gmock/gmock.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "gtest/gtest.h"
...
@@ -171,7 +171,7 @@ Admittedly, this test is contrived and doesn't do much. You can easily achieve t
...
@@ -171,7 +171,7 @@ Admittedly, this test is contrived and doesn't do much. You can easily achieve t
## Using Google Mock with Any Testing Framework ##
## Using Google Mock with Any Testing Framework ##
If you want to use something other than Google Test (e.g. [CppUnit](http://sourceforge.net/projects/cppunit/) or
If you want to use something other than Google Test (e.g. [CppUnit](http://sourceforge.net/projects/cppunit/) or
[CxxTest](https://cxxtest.com/)) as your testing framework, just change the `main()` function in the previous section to:
[CxxTest](https://cxxtest.com/)) as your testing framework, just change the `main()` function in the previous section to:
```
```cpp
intmain(intargc,char**argv){
intmain(intargc,char**argv){
// The following line causes Google Mock to throw an exception on failure,
// The following line causes Google Mock to throw an exception on failure,
// which will be interpreted by your testing framework as a test failure.
// which will be interpreted by your testing framework as a test failure.
...
@@ -203,7 +203,7 @@ The key to using a mock object successfully is to set the _right expectations_ o
...
@@ -203,7 +203,7 @@ The key to using a mock object successfully is to set the _right expectations_ o
## General Syntax ##
## General Syntax ##
In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is:
In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is:
```
```cpp
EXPECT_CALL(mock_object,method(matchers))
EXPECT_CALL(mock_object,method(matchers))
.Times(cardinality)
.Times(cardinality)
.WillOnce(action)
.WillOnce(action)
...
@@ -216,7 +216,7 @@ The macro can be followed by some optional _clauses_ that provide more informati
...
@@ -216,7 +216,7 @@ The macro can be followed by some optional _clauses_ that provide more informati
This syntax is designed to make an expectation read like English. For example, you can probably guess that
This syntax is designed to make an expectation read like English. For example, you can probably guess that
```
```cpp
using::testing::Return;
using::testing::Return;
...
...
EXPECT_CALL(turtle,GetX())
EXPECT_CALL(turtle,GetX())
...
@@ -233,14 +233,14 @@ says that the `turtle` object's `GetX()` method will be called five times, it wi
...
@@ -233,14 +233,14 @@ says that the `turtle` object's `GetX()` method will be called five times, it wi
## Matchers: What Arguments Do We Expect? ##
## Matchers: What Arguments Do We Expect? ##
When a mock function takes arguments, we must specify what arguments we are expecting; for example:
When a mock function takes arguments, we must specify what arguments we are expecting; for example:
```
```cpp
// Expects the turtle to move forward by 100 units.
// Expects the turtle to move forward by 100 units.
EXPECT_CALL(turtle,Forward(100));
EXPECT_CALL(turtle,Forward(100));
```
```
Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes":
Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes":
A list of built-in matchers can be found in the [CheatSheet](CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher:
A list of built-in matchers can be found in the [CheatSheet](CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher:
```
```cpp
using::testing::Ge;
using::testing::Ge;
...
...
EXPECT_CALL(turtle,Forward(Ge(100)));
EXPECT_CALL(turtle,Forward(Ge(100)));
...
@@ -281,7 +281,7 @@ First, if the return type of a mock function is a built-in type or a pointer, th
...
@@ -281,7 +281,7 @@ First, if the return type of a mock function is a built-in type or a pointer, th
Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example,
Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example,
```
```cpp
using::testing::Return;
using::testing::Return;
...
...
EXPECT_CALL(turtle,GetX())
EXPECT_CALL(turtle,GetX())
...
@@ -292,7 +292,7 @@ EXPECT_CALL(turtle, GetX())
...
@@ -292,7 +292,7 @@ EXPECT_CALL(turtle, GetX())
This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively.
This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively.
```
```cpp
using::testing::Return;
using::testing::Return;
...
...
EXPECT_CALL(turtle,GetY())
EXPECT_CALL(turtle,GetY())
...
@@ -309,7 +309,7 @@ What can we do inside `WillOnce()` besides `Return()`? You can return a referenc
...
@@ -309,7 +309,7 @@ What can we do inside `WillOnce()` besides `Return()`? You can return a referenc
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want:
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want:
```
```cpp
intn=100;
intn=100;
EXPECT_CALL(turtle,GetX())
EXPECT_CALL(turtle,GetX())
.Times(4)
.Times(4)
...
@@ -320,7 +320,7 @@ Instead of returning 100, 101, 102, ..., consecutively, this mock function will
...
@@ -320,7 +320,7 @@ Instead of returning 100, 101, 102, ..., consecutively, this mock function will
Time for another quiz! What do you think the following means?
Time for another quiz! What do you think the following means?
```
```cpp
using::testing::Return;
using::testing::Return;
...
...
EXPECT_CALL(turtle,GetY())
EXPECT_CALL(turtle,GetY())
...
@@ -335,7 +335,7 @@ So far we've only shown examples where you have a single expectation. More reali
...
@@ -335,7 +335,7 @@ So far we've only shown examples where you have a single expectation. More reali
By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example:
By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example:
```
```cpp
using::testing::_;
using::testing::_;
...
...
EXPECT_CALL(turtle,Forward(_));// #1
EXPECT_CALL(turtle,Forward(_));// #1
...
@@ -352,7 +352,7 @@ By default, an expectation can match a call even though an earlier expectation h
...
@@ -352,7 +352,7 @@ By default, an expectation can match a call even though an earlier expectation h
Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy:
Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy:
```
```cpp
using::testing::InSequence;
using::testing::InSequence;
...
...
TEST(FooTest,DrawsLineSegment){
TEST(FooTest,DrawsLineSegment){
...
@@ -379,7 +379,7 @@ Now let's do a quick quiz to see how well you can use this mock stuff already. H
...
@@ -379,7 +379,7 @@ Now let's do a quick quiz to see how well you can use this mock stuff already. H
After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!):
After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!):
```
```cpp
using::testing::_;
using::testing::_;
...
...
EXPECT_CALL(turtle,GoTo(_,_))// #1
EXPECT_CALL(turtle,GoTo(_,_))// #1
...
@@ -394,7 +394,7 @@ This example shows that **expectations in Google Mock are "sticky" by default**,
...
@@ -394,7 +394,7 @@ This example shows that **expectations in Google Mock are "sticky" by default**,
Simple? Let's see if you've really understood it: what does the following code say?
Simple? Let's see if you've really understood it: what does the following code say?
```
```cpp
using::testing::Return;
using::testing::Return;
...
...
for(inti=n;i>0;i--){
for(inti=n;i>0;i--){
...
@@ -407,7 +407,7 @@ If you think it says that `turtle.GetX()` will be called `n` times and will retu
...
@@ -407,7 +407,7 @@ If you think it says that `turtle.GetX()` will be called `n` times and will retu
One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated:
One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated:
```
```cpp
using::testing::Return;
using::testing::Return;
...
...
for(inti=n;i>0;i--){
for(inti=n;i>0;i--){
...
@@ -419,7 +419,7 @@ for (int i = n; i > 0; i--) {
...
@@ -419,7 +419,7 @@ for (int i = n; i > 0; i--) {
And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence:
And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: