|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. |
## Generic Comparison ##
|`Eq(value)` or `value`|`argument == value`|
| Matcher | Description |
|:---------------------|:------------------|
|`Eq(value)` or `value`|`argument == value`|
|`Ge(value)` |`argument >= value`|
|`Gt(value)` |`argument > value` |
|`Le(value)` |`argument <= value`|
@ -178,8 +181,7 @@ divided into several categories:
|`Ne(value)` |`argument != value`|
|`IsNull()` |`argument` is a `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
type T with a value matching `m`.|
|`VariantWith<T>(m)` |`argument` is `variant<>` that holds the alternative of type T with a value matching `m`.|
|`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.|
@ -192,11 +194,12 @@ matcher will be changed.
## Floating-Point Matchers ##
|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.|
|`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. |
|`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
[Google Test](../../googletest/)). They
@ -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
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.|
|`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. |
|`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. |
|`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.|
|`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 ##
The `argument` can be either a C string or a C++ string object:
|`ContainsRegex(string)`|`argument` matches the given regular expression.|
|`ContainsRegex(string)`|`argument` matches the given regular expression. |
|`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.|
|`StartsWith(prefix)` |`argument` starts with string `prefix`. |
|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. |
|`StartsWith(prefix)` |`argument` starts with string `prefix`. |
|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. |
|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.|
|`StrEq(string)` |`argument` is equal to `string`. |
|`StrNe(string)` |`argument` is not equal to `string`. |
|`StrEq(string)` |`argument` is equal to `string`. |
|`StrNe(string)` |`argument` is not equal to `string`. |
`ContainsRegex()` and `MatchesRegex()` use the regular expression
syntax defined
@ -240,18 +245,19 @@ Most STL-style containers support `==`, so you can use
container exactly. If you want to write the elements in-line,
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. |
| `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. |
| `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. |
| `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. |
| `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. |
| `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. |
| `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))`. |
Notes:
@ -262,7 +268,7 @@ Notes:
* 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:
|`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`.|
|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. |
|`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`.|
|`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 ##
|`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_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:
## 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`.|
|`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 #
@ -359,77 +375,83 @@ You can make a matcher from one or more other matchers:
## Returning a Value ##
| Matcher | Description |
|:--------|:------------|
|`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.|
|`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.|
|`ReturnNull()`|Return a null pointer.|
|`ReturnNull()`|Return a null pointer.|
|`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.|
## Side Effects ##
| Matcher | Description |
|:--------|:------------|
|`Assign(&variable, value)`|Assign `value` to variable.|
| `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`. |
| `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. |
|`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`.|
|`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. |
|`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.|
|`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`.|
|`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 ##
| 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(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(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. |
|`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(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.|
The return value of the invoked function is used as the return value
of the action.
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.
## 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. |
|`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. |
|`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. |
|`WithoutArgs(a)` |Perform action `a` without any arguments. |
|`WithoutArgs(a)` |Perform action `a` without any arguments. |
## Defining Actions ##
| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
@ -49,7 +49,7 @@ Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/
# 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:
```
```cpp
class Turtle {
...
virtual ~Turtle() {}
@ -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:
```
```cpp
#include "gmock/gmock.h" // Brings in Google Mock.
class MockTurtle : public Turtle {
public:
@ -125,7 +125,7 @@ Once you have a mock class, using it is easy. The typical work flow is:
Here's an example:
```
```cpp
#include "path/to/mock-turtle.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
@ -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 ##
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:
```
```cpp
int main(int argc, char** argv) {
// The following line causes Google Mock to throw an exception on 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
## General Syntax ##
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))
.Times(cardinality)
.WillOnce(action)
@ -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
```
```cpp
using ::testing::Return;
...
EXPECT_CALL(turtle, GetX())
@ -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? ##
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.
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":
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;
...
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
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;
...
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.
```
```cpp
using ::testing::Return;
...
EXPECT_CALL(turtle, GetY())
@ -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:
```
```cpp
int n = 100;
EXPECT_CALL(turtle, GetX())
.Times(4)
@ -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?
```
```cpp
using ::testing::Return;
...
EXPECT_CALL(turtle, GetY())
@ -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:
```
```cpp
using ::testing::_;
...
EXPECT_CALL(turtle, Forward(_)); // #1
@ -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:
```
```cpp
using ::testing::InSequence;
...
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
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::_;
...
EXPECT_CALL(turtle, GoTo(_, _)) // #1
@ -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?
```
```cpp
using ::testing::Return;
...
for (int i = n; i > 0; i--) {
@ -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:
```
```cpp
using ::testing::Return;
...
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: