aboutsummaryrefslogtreecommitdiffstats
path: root/googlemock
diff options
context:
space:
mode:
Diffstat (limited to 'googlemock')
-rw-r--r--googlemock/docs/cheat_sheet.md1038
-rw-r--r--googlemock/docs/documentation.md2
-rw-r--r--googlemock/docs/frequently_asked_questions.md556
-rw-r--r--googlemock/docs/gmock_faq.md392
4 files changed, 1050 insertions, 938 deletions
diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md
index d09d910c..ea46a68c 100644
--- a/googlemock/docs/cheat_sheet.md
+++ b/googlemock/docs/cheat_sheet.md
@@ -1,10 +1,13 @@
+## gMock Cheat Sheet
+<!-- GOOGLETEST_CM0018 DO NOT DELETE -->
-# Defining a Mock Class #
+### Defining a Mock Class
-## Mocking a Normal Class ##
+#### Mocking a Normal Class {#MockClass}
Given
+
```cpp
class Foo {
...
@@ -15,72 +18,97 @@ class Foo {
virtual bool Process(Bar elem, int count) = 0;
};
```
+
(note that `~Foo()` **must** be virtual) we can define its mock as
+
```cpp
#include "gmock/gmock.h"
class MockFoo : public Foo {
- MOCK_CONST_METHOD0(GetSize, int());
- MOCK_METHOD1(Describe, string(const char* name));
- MOCK_METHOD1(Describe, string(int type));
- MOCK_METHOD2(Process, bool(Bar elem, int count));
+ ...
+ MOCK_METHOD(int, GetSize, (), (const, override));
+ MOCK_METHOD(string, Describe, (const char* name), (override));
+ MOCK_METHOD(string, Describe, (int type), (override));
+ MOCK_METHOD(bool, Process, (Bar elem, int count), (override));
};
```
-To create a "nice" mock object which ignores all uninteresting calls,
-or a "strict" mock object, which treats them as failures:
+To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock,
+which warns on all uninteresting calls, or a "strict" mock, which treats them as
+failures:
+
```cpp
-NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo.
-StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
+using ::testing::NiceMock;
+using ::testing::NaggyMock;
+using ::testing::StrictMock;
+
+NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo.
+NaggyMock<MockFoo> naggy_foo; // The type is a subclass of MockFoo.
+StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
```
-## Mocking a Class Template ##
+**Note:** A mock object is currently naggy by default. We may make it nice by
+default in the future.
+
+#### Mocking a Class Template {#MockTemplate}
+
+Class templates can be mocked just like any class.
To mock
+
```cpp
template <typename Elem>
class StackInterface {
- public:
...
virtual ~StackInterface();
virtual int GetSize() const = 0;
virtual void Push(const Elem& x) = 0;
};
```
-(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros:
+
+(note that all member functions that are mocked, including `~StackInterface()`
+**must** be virtual).
+
```cpp
template <typename Elem>
class MockStack : public StackInterface<Elem> {
- public:
...
- MOCK_CONST_METHOD0_T(GetSize, int());
- MOCK_METHOD1_T(Push, void(const Elem& x));
+ MOCK_METHOD(int, GetSize, (), (const, override));
+ MOCK_METHOD(void, Push, (const Elem& x), (override));
};
```
-## Specifying Calling Conventions for Mock Functions ##
+#### Specifying Calling Conventions for Mock Functions
+
+If your mock function doesn't use the default calling convention, you can
+specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter.
+For example,
-If your mock function doesn't use the default calling convention, you
-can specify it by appending `_WITH_CALLTYPE` to any of the macros
-described in the previous two sections and supplying the calling
-convention as the first argument to the macro. For example,
```cpp
- MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n));
- MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y));
+ MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE)));
+ MOCK_METHOD(int, Bar, (double x, double y),
+ (const, Calltype(STDMETHODCALLTYPE)));
```
+
where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
-# Using Mocks in Tests #
+### Using Mocks in Tests {#UsingMocks}
-The typical flow is:
- 1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted.
- 1. Create the mock objects.
- 1. Optionally, set the default actions of the mock objects.
- 1. Set your expectations on the mock objects (How will they be called? What wil they do?).
- 1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](../../googletest/) assertions.
- 1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied.
+The typical work flow is:
+
+1. Import the gMock names you need to use. All gMock symbols are in the
+ `testing` namespace unless they are macros or otherwise noted.
+2. Create the mock objects.
+3. Optionally, set the default actions of the mock objects.
+4. Set your expectations on the mock objects (How will they be called? What
+ will they do?).
+5. Exercise code that uses the mock objects; if necessary, check the result
+ using googletest assertions.
+6. When a mock object is destructed, gMock automatically verifies that all
+ expectations on it have been satisfied.
+
+Here's an example:
-Here is an example:
```cpp
using ::testing::Return; // #1
@@ -100,382 +128,618 @@ TEST(BarTest, DoesThis) {
} // #6
```
-# Setting Default Actions #
+### Setting Default Actions {#OnCall}
-Google Mock has a **built-in default action** for any function that
-returns `void`, `bool`, a numeric value, or a pointer.
+gMock has a **built-in default action** for any function that returns `void`,
+`bool`, a numeric value, or a pointer. In C++11, it will additionally returns
+the default-constructed value, if one exists for the given type.
+
+To customize the default action for functions with return type *`T`*:
-To customize the default action for functions with return type `T` globally:
```cpp
using ::testing::DefaultValue;
// Sets the default value to be returned. T must be CopyConstructible.
DefaultValue<T>::Set(value);
// Sets a factory. Will be invoked on demand. T must be MoveConstructible.
-// T MakeT();
+// T MakeT();
DefaultValue<T>::SetFactory(&MakeT);
// ... use the mocks ...
// Resets the default value.
DefaultValue<T>::Clear();
```
-To customize the default action for a particular method, use `ON_CALL()`:
+Example usage:
+
```cpp
-ON_CALL(mock_object, method(matchers))
- .With(multi_argument_matcher) ?
- .WillByDefault(action);
+ // Sets the default action for return type std::unique_ptr<Buzz> to
+ // creating a new Buzz every time.
+ DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
+ [] { return MakeUnique<Buzz>(AccessLevel::kInternal); });
+
+ // When this fires, the default action of MakeBuzz() will run, which
+ // will return a new Buzz object.
+ EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
+
+ auto buzz1 = mock_buzzer_.MakeBuzz("hello");
+ auto buzz2 = mock_buzzer_.MakeBuzz("hello");
+ EXPECT_NE(nullptr, buzz1);
+ EXPECT_NE(nullptr, buzz2);
+ EXPECT_NE(buzz1, buzz2);
+
+ // Resets the default action for return type std::unique_ptr<Buzz>,
+ // to avoid interfere with other tests.
+ DefaultValue<std::unique_ptr<Buzz>>::Clear();
```
-# Setting Expectations #
+To customize the default action for a particular method of a specific mock
+object, use `ON_CALL()`. `ON_CALL()` has a similar syntax to `EXPECT_CALL()`,
+but it is used for setting default behaviors (when you do not require that the
+mock method is called). See go/prefer-on-call for a more detailed discussion.
-`EXPECT_CALL()` sets **expectations** on a mock method (How will it be
-called? What will it do?):
```cpp
-EXPECT_CALL(mock_object, method(matchers))
- .With(multi_argument_matcher) ?
- .Times(cardinality) ?
- .InSequence(sequences) *
- .After(expectations) *
- .WillOnce(action) *
- .WillRepeatedly(action) ?
- .RetiresOnSaturation(); ?
+ON_CALL(mock-object, method(matchers))
+ .With(multi-argument-matcher) ?
+ .WillByDefault(action);
```
-If `Times()` is omitted, the cardinality is assumed to be:
+### Setting Expectations {#ExpectCall}
- * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`;
- * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or
- * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0.
-
-A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time.
-
-# Matchers #
-
-A **matcher** matches a _single_ argument. You can use it inside
-`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value
-directly:
-
-| Matcher | Description |
-|:--------|:------------|
-| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. |
-| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. |
-
-Built-in matchers (where `argument` is the function argument) are
-divided into several categories:
-
-## Wildcard ##
-| Matcher | Description |
-|:--------|:------------|
-|`_`|`argument` can be any value of the correct type.|
-|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. |
-
-## Generic Comparison ##
-
-| Matcher | Description |
-|:---------------------|:------------------|
-|`Eq(value)` or `value`|`argument == value`|
-|`Ge(value)` |`argument >= value`|
-|`Gt(value)` |`argument > value` |
-|`Le(value)` |`argument <= value`|
-|`Lt(value)` |`argument < value` |
-|`Ne(value)` |`argument != value`|
-|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).|
-|`NotNull()` |`argument` is a non-null pointer (raw or smart).|
-|`Optional(m)` |`argument` is `optional<>` that contains 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.|
-
-Except `Ref()`, these matchers make a _copy_ of `value` in case it's
-modified or destructed later. If the compiler complains that `value`
-doesn't have a public copy constructor, try wrap it in `ByRef()`,
-e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure
-`non_copyable_value` is not changed afterwards, or the meaning of your
-matcher will be changed.
-
-## Floating-Point Matchers ##
-
-| Matcher | Description |
-|:-------------------|:---------------------------------------------------------------------------------------------------------|
-|`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
-automatically pick a reasonable error bound based on the absolute
-value of the expected value. `DoubleEq()` and `FloatEq()` conform to
-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.|
-
-## String Matchers ##
-
-The `argument` can be either a C string or a C++ string object:
-
-| Matcher | Description |
-|:----------------------|:--------------------------------------------------|
-|`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. |
-|`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`. |
-
-`ContainsRegex()` and `MatchesRegex()` use the regular expression
-syntax defined
-[here](../../googletest/docs/advanced.md#regular-expression-syntax).
-`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide
-strings as well.
-
-## Container Matchers ##
-
-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 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. |
-| `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()`). |
-| `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))`. |
-| `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. |
-| `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:
-
- * These matchers can also match:
- 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and
- 1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#multiargument-matchers)).
- * 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:
+`EXPECT_CALL()` sets **expectations** on a mock method (How will it be called?
+What will it do?):
```cpp
-using ::testing::get;
-MATCHER(FooEq, "") {
- return get<0>(arg).Equals(get<1>(arg));
-}
-...
-EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));
+EXPECT_CALL(mock-object, method (matchers)?)
+ .With(multi-argument-matcher) ?
+ .Times(cardinality) ?
+ .InSequence(sequences) *
+ .After(expectations) *
+ .WillOnce(action) *
+ .WillRepeatedly(action) ?
+ .RetiresOnSaturation(); ?
```
-## Member Matchers ##
-
-| Matcher | Description |
-|:--------|:------------|
-|`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`.|
-|`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 ##
-
-| Matcher | Description |
-|:---------------|:---------------------------------------------------------------------|
-|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.|
+If `(matchers)` is omitted, the expectation is the same as if the matchers were
+set to anything matchers (for example, `(_, _, _, _)` for a four-arg method).
-## Pointer Matchers ##
-
-| Matcher | Description |
-|:------------------------|:-----------------------------------------------------------------------------------------------|
-|`Pointee(m)` |`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.|
-|`WhenDynamicCastTo<T>(m)`| when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`. |
-
-## Multiargument Matchers ##
+If `Times()` is omitted, the cardinality is assumed to be:
-Technically, all matchers match a _single_ value. A "multi-argument"
-matcher is just one that matches a _tuple_. The following matchers can
-be used to match a tuple `(x, y)`:
+* `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`;
+* `Times(n)` when there are `n` `WillOnce()`s but no `WillRepeatedly()`, where
+ `n` >= 1; or
+* `Times(AtLeast(n))` when there are `n` `WillOnce()`s and a
+ `WillRepeatedly()`, where `n` >= 0.
+
+A method with no `EXPECT_CALL()` is free to be invoked *any number of times*,
+and the default action will be taken each time.
+
+### Matchers {#MatcherList}
+
+<!-- GOOGLETEST_CM0019 DO NOT DELETE -->
+
+A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or
+`EXPECT_CALL()`, or use it to validate a value directly:
+
+| Matcher | Description |
+| :----------------------------------- | :------------------------------------ |
+| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches |
+: : `matcher`. :
+| `ASSERT_THAT(actual_value, matcher)` | The same as |
+: : `EXPECT_THAT(actual_value, matcher)`, :
+: : except that it generates a **fatal** :
+: : failure. :
+
+Built-in matchers (where `argument` is the function argument) are divided into
+several categories:
+
+## Wildcard
+
+Matcher | Description
+:-------------------------- | :-----------------------------------------------
+`_` | `argument` can be any value of the correct type.
+`A<type>()` or `An<type>()` | `argument` can be any value of type `type`.
+
+#### Generic Comparison
+
+| Matcher | Description |
+| :--------------------- | :-------------------------------------------------- |
+| `Eq(value)` or `value` | `argument == value` |
+| `Ge(value)` | `argument >= value` |
+| `Gt(value)` | `argument > value` |
+| `Le(value)` | `argument <= value` |
+| `Lt(value)` | `argument < value` |
+| `Ne(value)` | `argument != value` |
+| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). |
+| `NotNull()` | `argument` is a non-null pointer (raw or smart). |
+| `Optional(m)` | `argument` is `optional<>` that contains 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. :
+
+Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or
+destructed later. If the compiler complains that `value` doesn't have a public
+copy constructor, try wrap it in `ByRef()`, e.g.
+`Eq(ByRef(non_copyable_value))`. If you do that, make sure `non_copyable_value`
+is not changed afterwards, or the meaning of your matcher will be changed.
+
+#### Floating-Point Matchers {#FpMatchers}
+
+| Matcher | Description |
+| :------------------------------- | :--------------------------------- |
+| `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 googletest).
+They automatically pick a reasonable error bound based on the absolute value of
+the expected value. `DoubleEq()` and `FloatEq()` conform to 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, | `argument` is a `double` value close |
+: max_abs_error)` : 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, | `argument` is a `double` value close |
+: max_abs_error)` : to `a_double` (absolute error <= :
+: : `max_abs_error`), treating two NaNs as :
+: : equal. :
+| `NanSensitiveFloatNear(a_float, | `argument` is a `float` value close to |
+: max_abs_error)` : `a_float` (absolute error <= :
+: : `max_abs_error`), treating two NaNs as :
+: : equal. :
+
+#### String Matchers
-| Matcher | Description |
-|:--------|:------------|
-|`Eq()`|`x == y`|
-|`Ge()`|`x >= y`|
-|`Gt()`|`x > y` |
-|`Le()`|`x <= y`|
-|`Lt()`|`x < y` |
-|`Ne()`|`x != y`|
+The `argument` can be either a C string or a C++ string object:
-You can use the following selectors to pick a subset of the arguments
-(or reorder them) to participate in the matching:
+| Matcher | Description |
+| :---------------------- | :------------------------------------------------- |
+| `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. |
+| `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`. |
+
+`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
+use the regular expression syntax defined
+[here](http://go/gunit-advanced-regex). `StrCaseEq()`, `StrCaseNe()`, `StrEq()`,
+and `StrNe()` work for wide strings as well.
+
+#### Container Matchers
+
+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
+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. :
+| `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 | The same as `ElementsAre()` except |
+: })`, `ElementsAreArray(array)`, or : that the expected element :
+: `ElementsAreArray(array, count)` : values/matchers come from an :
+: : initializer list, STL-style :
+: : container, or C-style array. :
+| `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))`. :
+| `UnorderedElementsAre(e0, e1, ..., | `argument` has `n + 1` elements, and |
+: en)` : 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, | The same as `UnorderedElementsAre()` |
+: ..., en })`, : except that the expected element :
+: `UnorderedElementsAreArray(array)`, : values/matchers come from an :
+: or `UnorderedElementsAreArray(array, : initializer list, STL-style :
+: count)` : 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. :
+| `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))`. :
-| Matcher | Description |
-|:--------|:------------|
-|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.|
-|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.|
+**Notes:**
-## Composite Matchers ##
+* These matchers can also match:
+ 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`),
+ and
+ 2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer,
+ int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)).
+* The array being matched may be multi-dimensional (i.e. its elements can be
+ arrays).
+* `m` in `Pointwise(m, ...)` should be a 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, to compare two `Foo`
+ containers where `Foo` doesn't support `operator==`, one might write:
+
+ ```cpp
+ using ::std::get;
+ MATCHER(FooEq, "") {
+ return std::get<0>(arg).Equals(std::get<1>(arg));
+ }
+ ...
+ EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));
+ ```
+
+#### Member Matchers
+
+| Matcher | Description |
+| :------------------------------ | :----------------------------------------- |
+| `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`. :
+| `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, Functor, or Callback
+
+| Matcher | Description |
+| :--------------- | :------------------------------------------------ |
+| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a |
+: : function or functor. :
+
+#### Pointer Matchers
+
+| Matcher | Description |
+| :------------------------ | :---------------------------------------------- |
+| `Pointee(m)` | `argument` (either a smart pointer or a raw |
+: : pointer) points to a value that matches matcher :
+: : `m`. :
+| `WhenDynamicCastTo<T>(m)` | when `argument` is passed through |
+: : `dynamic_cast<T>()`, it matches matcher `m`. :
+
+#### Multi-argument Matchers {#MultiArgMatchers}
+
+Technically, all matchers match a *single* value. A "multi-argument" matcher is
+just one that matches a *tuple*. The following matchers can be used to match a
+tuple `(x, y)`:
+
+Matcher | Description
+:------ | :----------
+`Eq()` | `x == y`
+`Ge()` | `x >= y`
+`Gt()` | `x > y`
+`Le()` | `x <= y`
+`Lt()` | `x < y`
+`Ne()` | `x != y`
+
+You can use the following selectors to pick a subset of the arguments (or
+reorder them) to participate in the matching:
+
+| Matcher | Description |
+| :------------------------- | :---------------------------------------------- |
+| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in |
+: : `.With(AllArgs(m))`. :
+| `Args<N1, N2, ..., Nk>(m)` | The tuple of the `k` selected (using 0-based |
+: : indices) arguments matches `m`, e.g. `Args<1, :
+: : 2>(Eq())`. :
+
+#### Composite Matchers
You can make a matcher from one or more other matchers:
-| Matcher | Description |
-|:-----------------------|:------------------------------------------------------------|
-|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`. |
-|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.|
-|`Not(m)` |`argument` doesn't match matcher `m`. |
-
-## Adapters for Matchers ##
-
-| Matcher | Description |
-|:--------|:------------|
-|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.|
-|`SafeMatcherCast<T>(m)`| [safely casts](cook_book.md#casting-matchers) matcher `m` to type `Matcher<T>`.|
-|`Truly(predicate)`|`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.|
-
-## Matchers as Predicates ##
-
-| Matcher | Description |
-|:--------|:------------|
-|`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 `value` matches `m`, explaining the result to `result_listener`.|
-|`Value(value, m)`|evaluates to `true` if `value` matches `m`.|
-
-## Defining Matchers ##
-
-| Matcher | Description |
-|:--------|:------------|
-| `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 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 | Description |
+| :----------------------- | :---------------------------------------------- |
+| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to |
+: : `mn`. :
+| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers |
+: : `m1` to `mn`. :
+| `Not(m)` | `argument` doesn't match matcher `m`. |
+
+#### Adapters for Matchers
+
+| Matcher | Description |
+| :---------------------- | :------------------------------------ |
+| `MatcherCast<T>(m)` | casts matcher `m` to type |
+: : `Matcher<T>`. :
+| `SafeMatcherCast<T>(m)` | [safely |
+: : casts](cook_book.md#casting-matchers) :
+: : matcher `m` to type `Matcher<T>`. :
+| `Truly(predicate)` | `predicate(argument)` returns |
+: : something considered by C++ to be :
+: : true, where `predicate` is a function :
+: : or functor. :
+
+`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`,
+which must be a permanent callback.
+
+#### Matchers as Predicates {#MatchersAsPredicatesCheat}
+
+| Matcher | Description |
+| :---------------------------- | :------------------------------------------ |
+| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. |
+: : You can use `Matches(m)` alone as a unary :
+: : functor. :
+| `ExplainMatchResult(m, value, | evaluates to `true` if `value` matches `m`, |
+: result_listener)` : explaining the result to `result_listener`. :
+| `Value(value, m)` | evaluates to `true` if `value` matches `m`. |
+
+#### Defining Matchers
+
+| Matcher | Description |
+| :----------------------------------- | :------------------------------------ |
+| `MATCHER(IsEven, "") { return (arg % | Defines a matcher `IsEven()` to match |
+: 2) == 0; }` : an even number. :
+| `MATCHER_P(IsDivisibleBy, n, "") { | Defines a macher `IsDivisibleBy(n)` |
+: *result_listener << "where the : to match a number divisible by `n`. :
+: remainder is " << (arg % n); return : :
+: (arg % n) == 0; }` : :
+| `MATCHER_P2(IsBetween, a, b, | Defines a matcher `IsBetween(a, b)` |
+: std\:\:string(negation ? "isn't" \: : to match a value in the range [`a`, :
+: "is") + " between " + : `b`]. :
+: PrintToString(a) + " and " + : :
+: PrintToString(b)) { return a <= arg : :
+: && arg <= b; }` : :
**Notes:**
- 1. The `MATCHER*` macros cannot be used inside a function or class.
- 1. 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 being matched and the matcher parameters).
- 1. You can use `PrintToString(x)` to convert a value `x` of any type to a string.
+1. The `MATCHER*` macros cannot be used inside a function or class.
+1. 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
+ being matched and the matcher parameters).
+1. You can use `PrintToString(x)` to convert a value `x` of any type to a
+ string.
-## 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`.|
-|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`.|
+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`.
-# Actions #
+### Actions {#ActionList}
**Actions** specify what a mock function should do when invoked.
-## 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.|
-|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.|
-|`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. |
-|`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.|
-
-## 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.|
-|`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`:
-```cpp
- double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
- ...
- EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
-```
+#### 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. |
+| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. |
+| `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. :
+| `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. :
+
+#### Using a Function, Functor, Lambda, or Callback as an Action
+
+In the following, by "callable" we mean a free function, `std::function`,
+functor, lambda, or `google3`-style permanent callback.
+
+| 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, | Invoke the {method on the object with |
+: &class\:\:method)` : 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, | Invoke the method on the object, which |
+: &class\:\:method)` : takes no arguments. :
+| `InvokeArgument<N>(arg1, arg2, ..., | Invoke the mock function's `N`-th |
+: argk)` : (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 callable to be used with `Invoke*()`, you can declare any unused
+parameters as `Unused`:
-In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example,
```cpp
- InvokeArgument<2>(5, string("Hi"), ByRef(foo))
+using ::testing::Invoke;
+double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
+...
+EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
```
-calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference.
-## Default Action ##
+`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of
+`callback`, which must be permanent. The type of `callback` must be a base
+callback type instead of a derived one, e.g.
-| Matcher | Description |
-|:--------|:------------|
-|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).|
-
-**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error.
+```cpp
+ BlockingClosure* done = new BlockingClosure;
+ ... Invoke(done) ...; // This won't compile!
-## Composite Actions ##
+ Closure* done2 = new BlockingClosure;
+ ... Invoke(done2) ...; // This works.
+```
-| Matcher | Description |
-|:-----------------------------|:-----------------------------------------------------------------------------------------------------------------------------|
-|`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. |
+In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference,
+wrap it inside `ByRef()`. For example,
-## Defining Actions ##
+```cpp
+using ::testing::ByRef;
+using ::testing::InvokeArgument;
+...
+InvokeArgument<2>(5, string("Hi"), ByRef(foo))
+```
-| Matcher | Description |
-|:----------------------------------------------|:------------------------------------------------------------------------------------------|
-| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
-| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
-| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. |
+calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by
+value, and `foo` by reference.
+
+## Default Action
+
+| Matcher | Description |
+| :------------ | :----------------------------------------------------- |
+| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the |
+: : built-in one). :
+
+**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
+
+| Matcher | Description |
+| :----------------------------- | :------------------------------------------ |
+| `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. |
+
+## Defining Actions
+
+| Matcher | Description |
+| :--------------------------------- | :-------------------------------------- |
+| `ACTION(Sum) { return arg0 + arg1; | Defines an action `Sum()` to return the |
+: }` : sum of the mock function's argument #0 :
+: : and #1. :
+| `ACTION_P(Plus, n) { return arg0 + | Defines an action `Plus(n)` to return |
+: n; }` : the sum of the mock function's :
+: : argument #0 and `n`. :
+| `ACTION_Pk(Foo, p1, ..., pk) { | Defines a parameterized action `Foo(p1, |
+: statements; }` : ..., pk)` to execute the given :
+: : `statements`. :
The `ACTION*` macros cannot be used inside a function or class.
-# Cardinalities #
+### Cardinalities {#CardinalityList}
-These are used in `Times()` to specify how many times a mock function will be called:
+These are used in `Times()` to specify how many times a mock function will be
+called:
-| Matcher | Description |
-|:--------|:------------|
-|`AnyNumber()`|The function can be called any number of times.|
-|`AtLeast(n)`|The call is expected at least `n` times.|
-|`AtMost(n)`|The call is expected at most `n` times.|
-|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.|
-|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.|
+| Matcher | Description |
+| :---------------- | :----------------------------------------------------- |
+| `AnyNumber()` | The function can be called any number of times. |
+| `AtLeast(n)` | The call is expected at least `n` times. |
+| `AtMost(n)` | The call is expected at most `n` times. |
+| `Between(m, n)` | The call is expected between `m` and `n` (inclusive) |
+: : times. :
+| `Exactly(n) or n` | The call is expected exactly `n` times. In particular, |
+: : the call should never happen when `n` is 0. :
-# Expectation Order #
+### Expectation Order
-By default, the expectations can be matched in _any_ order. If some
-or all expectations must be matched in a given order, there are two
-ways to specify it. They can be used either independently or
-together.
+By default, the expectations can be matched in *any* order. If some or all
+expectations must be matched in a given order, there are two ways to specify it.
+They can be used either independently or together.
-## The After Clause ##
+#### The After Clause {#AfterClause}
```cpp
using ::testing::Expectation;
@@ -483,13 +747,14 @@ using ::testing::Expectation;
Expectation init_x = EXPECT_CALL(foo, InitX());
Expectation init_y = EXPECT_CALL(foo, InitY());
EXPECT_CALL(foo, Bar())
- .After(init_x, init_y);
+ .After(init_x, init_y);
```
-says that `Bar()` can be called only after both `InitX()` and
-`InitY()` have been called.
-If you don't know how many pre-requisites an expectation has when you
-write it, you can use an `ExpectationSet` to collect them:
+says that `Bar()` can be called only after both `InitX()` and `InitY()` have
+been called.
+
+If you don't know how many pre-requisites an expectation has when you write it,
+you can use an `ExpectationSet` to collect them:
```cpp
using ::testing::ExpectationSet;
@@ -499,24 +764,24 @@ for (int i = 0; i < element_count; i++) {
all_inits += EXPECT_CALL(foo, InitElement(i));
}
EXPECT_CALL(foo, Bar())
- .After(all_inits);
+ .After(all_inits);
```
-says that `Bar()` can be called only after all elements have been
-initialized (but we don't care about which elements get initialized
-before the others).
-Modifying an `ExpectationSet` after using it in an `.After()` doesn't
-affect the meaning of the `.After()`.
+says that `Bar()` can be called only after all elements have been initialized
+(but we don't care about which elements get initialized before the others).
+
+Modifying an `ExpectationSet` after using it in an `.After()` doesn't affect the
+meaning of the `.After()`.
-## Sequences ##
+#### Sequences {#UsingSequences}
-When you have a long chain of sequential expectations, it's easier to
-specify the order using **sequences**, which don't require you to given
-each expectation in the chain a different name. <i>All expected<br>
-calls</i> in the same sequence must occur in the order they are
-specified.
+When you have a long chain of sequential expectations, it's easier to specify
+the order using **sequences**, which don't require you to given each expectation
+in the chain a different name. *All expected calls* in the same sequence must
+occur in the order they are specified.
```cpp
+using ::testing::Return;
using ::testing::Sequence;
Sequence s1, s2;
...
@@ -530,14 +795,16 @@ EXPECT_CALL(foo, Describe(A<const char*>()))
.InSequence(s2)
.WillOnce(Return("dummy"));
```
-says that `Reset()` must be called before _both_ `GetSize()` _and_
-`Describe()`, and the latter two can occur in any order.
+
+says that `Reset()` must be called before *both* `GetSize()` *and* `Describe()`,
+and the latter two can occur in any order.
To put many expectations in a sequence conveniently:
+
```cpp
using ::testing::InSequence;
{
- InSequence dummy;
+ InSequence seq;
EXPECT_CALL(...)...;
EXPECT_CALL(...)...;
@@ -545,12 +812,15 @@ using ::testing::InSequence;
EXPECT_CALL(...)...;
}
```
-says that all expected calls in the scope of `dummy` must occur in
-strict order. The name `dummy` is irrelevant.)
-# Verifying and Resetting a Mock #
+says that all expected calls in the scope of `seq` must occur in strict order.
+The name `seq` is irrelevant.
+
+### Verifying and Resetting a Mock
+
+gMock will verify the expectations on a mock object when it is destructed, or
+you can do it earlier:
-Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier:
```cpp
using ::testing::Mock;
...
@@ -564,26 +834,32 @@ Mock::VerifyAndClearExpectations(&mock_obj);
Mock::VerifyAndClear(&mock_obj);
```
-You can also tell Google Mock that a mock object can be leaked and doesn't
-need to be verified:
+You can also tell gMock that a mock object can be leaked and doesn't need to be
+verified:
+
```cpp
Mock::AllowLeak(&mock_obj);
```
-# Mock Classes #
+### Mock Classes
+
+gMock defines a convenient mock class template
-Google Mock defines a convenient mock class template
```cpp
class MockFunction<R(A1, ..., An)> {
public:
- MOCK_METHODn(Call, R(A1, ..., An));
+ MOCK_METHOD(R, Call, (A1, ..., An));
};
```
+
See this [recipe](cook_book.md#using-check-points) for one application of it.
-# Flags #
+### Flags
-| Flag | Description |
-|:--------|:------------|
-| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
-| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
+| Flag | Description |
+| :----------------------------- | :---------------------------------------- |
+| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as |
+: : failures. :
+| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, |
+: : `warning`, or `error`) of Google Mock :
+: : messages. :
diff --git a/googlemock/docs/documentation.md b/googlemock/docs/documentation.md
index 831598cc..3e92882c 100644
--- a/googlemock/docs/documentation.md
+++ b/googlemock/docs/documentation.md
@@ -8,7 +8,7 @@ the respective git branch/tag).**
* [CheatSheet](cheat_sheet.md) -- a quick reference.
* [CookBook](cook_book.md) -- recipes for doing various tasks using Google Mock.
* [DesignDoc](design_doc.md) -- design of and rationale behind some Google Mock features.
- * [FrequentlyAskedQuestions](frequently_asked_questions.md) and [KnownIssues](known_issues.md) -- check here before asking a question on the mailing list.
+ * [FrequentlyAskedQuestions](gmock_faq.md) and [KnownIssues](known_issues.md) -- check here before asking a question on the mailing list.
To contribute code to Google Mock, read:
diff --git a/googlemock/docs/frequently_asked_questions.md b/googlemock/docs/frequently_asked_questions.md
deleted file mode 100644
index de1ad2a2..00000000
--- a/googlemock/docs/frequently_asked_questions.md
+++ /dev/null
@@ -1,556 +0,0 @@
-
-
-Please send your questions to the
-[googlemock](http://groups.google.com/group/googlemock) discussion
-group. If you need help with compiler errors, make sure you have
-tried [Google Mock Doctor](#how-am-i-supposed-to-make-sense-of-these-horrible-template-errors) first.
-
-## When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? ##
-
-In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](cook_book.md#mocking-nonvirtual-methods).
-
-## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ##
-
-After version 1.4.0 of Google Mock was released, we had an idea on how
-to make it easier to write matchers that can generate informative
-messages efficiently. We experimented with this idea and liked what
-we saw. Therefore we decided to implement it.
-
-Unfortunately, this means that if you have defined your own matchers
-by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`,
-your definitions will no longer compile. Matchers defined using the
-`MATCHER*` family of macros are not affected.
-
-Sorry for the hassle if your matchers are affected. We believe it's
-in everyone's long-term interest to make this change sooner than
-later. Fortunately, it's usually not hard to migrate an existing
-matcher to the new API. Here's what you need to do:
-
-If you wrote your matcher like this:
-```cpp
-// Old matcher definition that doesn't work with the latest
-// Google Mock.
-using ::testing::MatcherInterface;
-...
-class MyWonderfulMatcher : public MatcherInterface<MyType> {
- public:
- ...
- virtual bool Matches(MyType value) const {
- // Returns true if value matches.
- return value.GetFoo() > 5;
- }
- ...
-};
-```
-
-you'll need to change it to:
-```cpp
-// New matcher definition that works with the latest Google Mock.
-using ::testing::MatcherInterface;
-using ::testing::MatchResultListener;
-...
-class MyWonderfulMatcher : public MatcherInterface<MyType> {
- public:
- ...
- virtual bool MatchAndExplain(MyType value,
- MatchResultListener* listener) const {
- // Returns true if value matches.
- return value.GetFoo() > 5;
- }
- ...
-};
-```
-(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second
-argument of type `MatchResultListener*`.)
-
-If you were also using `ExplainMatchResultTo()` to improve the matcher
-message:
-```cpp
-// Old matcher definition that doesn't work with the lastest
-// Google Mock.
-using ::testing::MatcherInterface;
-...
-class MyWonderfulMatcher : public MatcherInterface<MyType> {
- public:
- ...
- virtual bool Matches(MyType value) const {
- // Returns true if value matches.
- return value.GetFoo() > 5;
- }
-
- virtual void ExplainMatchResultTo(MyType value,
- ::std::ostream* os) const {
- // Prints some helpful information to os to help
- // a user understand why value matches (or doesn't match).
- *os << "the Foo property is " << value.GetFoo();
- }
- ...
-};
-```
-
-you should move the logic of `ExplainMatchResultTo()` into
-`MatchAndExplain()`, using the `MatchResultListener` argument where
-the `::std::ostream` was used:
-```cpp
-// New matcher definition that works with the latest Google Mock.
-using ::testing::MatcherInterface;
-using ::testing::MatchResultListener;
-...
-class MyWonderfulMatcher : public MatcherInterface<MyType> {
- public:
- ...
- virtual bool MatchAndExplain(MyType value,
- MatchResultListener* listener) const {
- // Returns true if value matches.
- *listener << "the Foo property is " << value.GetFoo();
- return value.GetFoo() > 5;
- }
- ...
-};
-```
-
-If your matcher is defined using `MakePolymorphicMatcher()`:
-```cpp
-// Old matcher definition that doesn't work with the latest
-// Google Mock.
-using ::testing::MakePolymorphicMatcher;
-...
-class MyGreatMatcher {
- public:
- ...
- bool Matches(MyType value) const {
- // Returns true if value matches.
- return value.GetBar() < 42;
- }
- ...
-};
-... MakePolymorphicMatcher(MyGreatMatcher()) ...
-```
-
-you should rename the `Matches()` method to `MatchAndExplain()` and
-add a `MatchResultListener*` argument (the same as what you need to do
-for matchers defined by implementing `MatcherInterface`):
-```cpp
-// New matcher definition that works with the latest Google Mock.
-using ::testing::MakePolymorphicMatcher;
-using ::testing::MatchResultListener;
-...
-class MyGreatMatcher {
- public:
- ...
- bool MatchAndExplain(MyType value,
- MatchResultListener* listener) const {
- // Returns true if value matches.
- return value.GetBar() < 42;
- }
- ...
-};
-... MakePolymorphicMatcher(MyGreatMatcher()) ...
-```
-
-If your polymorphic matcher uses `ExplainMatchResultTo()` for better
-failure messages:
-```cpp
-// Old matcher definition that doesn't work with the latest
-// Google Mock.
-using ::testing::MakePolymorphicMatcher;
-...
-class MyGreatMatcher {
- public:
- ...
- bool Matches(MyType value) const {
- // Returns true if value matches.
- return value.GetBar() < 42;
- }
- ...
-};
-void ExplainMatchResultTo(const MyGreatMatcher& matcher,
- MyType value,
- ::std::ostream* os) {
- // Prints some helpful information to os to help
- // a user understand why value matches (or doesn't match).
- *os << "the Bar property is " << value.GetBar();
-}
-... MakePolymorphicMatcher(MyGreatMatcher()) ...
-```
-
-you'll need to move the logic inside `ExplainMatchResultTo()` to
-`MatchAndExplain()`:
-```cpp
-// New matcher definition that works with the latest Google Mock.
-using ::testing::MakePolymorphicMatcher;
-using ::testing::MatchResultListener;
-...
-class MyGreatMatcher {
- public:
- ...
- bool MatchAndExplain(MyType value,
- MatchResultListener* listener) const {
- // Returns true if value matches.
- *listener << "the Bar property is " << value.GetBar();
- return value.GetBar() < 42;
- }
- ...
-};
-... MakePolymorphicMatcher(MyGreatMatcher()) ...
-```
-
-For more information, you can read these
-[two](cook_book.md#writing-new-monomorphic-matchers)
-[recipes](cook_book.md#writing-new-polymorphic-matchers)
-from the cookbook. As always, you
-are welcome to post questions on `googlemock@googlegroups.com` if you
-need any help.
-
-## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ##
-
-Google Mock works out of the box with Google Test. However, it's easy
-to configure it to work with any testing framework of your choice.
-[Here](for_dummies.md#using-google-mock-with-any-testing-framework) is how.
-
-## How am I supposed to make sense of these horrible template errors? ##
-
-If you are confused by the compiler errors gcc threw at you,
-try consulting the _Google Mock Doctor_ tool first. What it does is to
-scan stdin for gcc error messages, and spit out diagnoses on the
-problems (we call them diseases) your code has.
-
-To "install", run command:
-```
-alias gmd='<path to googlemock>/scripts/gmock_doctor.py'
-```
-
-To use it, do:
-```
-<your-favorite-build-command> <your-test> 2>&1 | gmd
-```
-
-For example:
-```
-make my_test 2>&1 | gmd
-```
-
-Or you can run `gmd` and copy-n-paste gcc's error messages to it.
-
-## Can I mock a variadic function? ##
-
-You cannot mock a variadic function (i.e. a function taking ellipsis
-(`...`) arguments) directly in Google Mock.
-
-The problem is that in general, there is _no way_ for a mock object to
-know how many arguments are passed to the variadic method, and what
-the arguments' types are. Only the _author of the base class_ knows
-the protocol, and we cannot look into their head.
-
-Therefore, to mock such a function, the _user_ must teach the mock
-object how to figure out the number of arguments and their types. One
-way to do it is to provide overloaded versions of the function.
-
-Ellipsis arguments are inherited from C and not really a C++ feature.
-They are unsafe to use and don't work with arguments that have
-constructors or destructors. Therefore we recommend to avoid them in
-C++ as much as possible.
-
-
-## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ##
-
-When Google Mock detects a failure, it prints relevant information
-(the mock function arguments, the state of relevant expectations, and
-etc) to help the user debug. If another failure is detected, Google
-Mock will do the same, including printing the state of relevant
-expectations.
-
-Sometimes an expectation's state didn't change between two failures,
-and you'll see the same description of the state twice. They are
-however _not_ redundant, as they refer to _different points in time_.
-The fact they are the same _is_ interesting information.
-
-## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ##
-
-Does the class (hopefully a pure interface) you are mocking have a
-virtual destructor?
-
-Whenever you derive from a base class, make sure its destructor is
-virtual. Otherwise Bad Things will happen. Consider the following
-code:
-
-```cpp
-class Base {
- public:
- // Not virtual, but should be.
- ~Base() { ... }
- ...
-};
-
-class Derived : public Base {
- public:
- ...
- private:
- std::string value_;
-};
-
-...
- Base* p = new Derived;
- ...
- delete p; // Surprise! ~Base() will be called, but ~Derived() will not
- // - value_ is leaked.
-```
-
-By changing `~Base()` to virtual, `~Derived()` will be correctly
-called when `delete p` is executed, and the heap checker
-will be happy.
-
-## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ##
-
-When people complain about this, often they are referring to code like:
-
-```cpp
-// foo.Bar() should be called twice, return 1 the first time, and return
-// 2 the second time. However, I have to write the expectations in the
-// reverse order. This sucks big time!!!
-EXPECT_CALL(foo, Bar())
- .WillOnce(Return(2))
- .RetiresOnSaturation();
-EXPECT_CALL(foo, Bar())
- .WillOnce(Return(1))
- .RetiresOnSaturation();
-```
-
-The problem is that they didn't pick the **best** way to express the test's
-intent.
-
-By default, expectations don't have to be matched in _any_ particular
-order. If you want them to match in a certain order, you need to be
-explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's
-easy to accidentally over-specify your tests, and we want to make it
-harder to do so.
-
-There are two better ways to write the test spec. You could either
-put the expectations in sequence:
-
-```cpp
-// foo.Bar() should be called twice, return 1 the first time, and return
-// 2 the second time. Using a sequence, we can write the expectations
-// in their natural order.
-{
- InSequence s;
- EXPECT_CALL(foo, Bar())
- .WillOnce(Return(1))
- .RetiresOnSaturation();
- EXPECT_CALL(foo, Bar())
- .WillOnce(Return(2))
- .RetiresOnSaturation();
-}
-```
-
-or you can put the sequence of actions in the same expectation:
-
-```cpp
-// foo.Bar() should be called twice, return 1 the first time, and return
-// 2 the second time.
-EXPECT_CALL(foo, Bar())
- .WillOnce(Return(1))
- .WillOnce(Return(2))
- .RetiresOnSaturation();
-```
-
-Back to the original questions: why does Google Mock search the
-expectations (and `ON_CALL`s) from back to front? Because this
-allows a user to set up a mock's behavior for the common case early
-(e.g. in the mock's constructor or the test fixture's set-up phase)
-and customize it with more specific rules later. If Google Mock
-searches from front to back, this very useful pattern won't be
-possible.
-
-## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ##
-
-When choosing between being neat and being safe, we lean toward the
-latter. So the answer is that we think it's better to show the
-warning.
-
-Often people write `ON_CALL`s in the mock object's
-constructor or `SetUp()`, as the default behavior rarely changes from
-test to test. Then in the test body they set the expectations, which
-are often different for each test. Having an `ON_CALL` in the set-up
-part of a test doesn't mean that the calls are expected. If there's
-no `EXPECT_CALL` and the method is called, it's possibly an error. If
-we quietly let the call go through without notifying the user, bugs
-may creep in unnoticed.
-
-If, however, you are sure that the calls are OK, you can write
-
-```cpp
-EXPECT_CALL(foo, Bar(_))
- .WillRepeatedly(...);
-```
-
-instead of
-
-```cpp
-ON_CALL(foo, Bar(_))
- .WillByDefault(...);
-```
-
-This tells Google Mock that you do expect the calls and no warning should be
-printed.
-
-Also, you can control the verbosity using the `--gmock_verbose` flag.
-If you find the output too noisy when debugging, just choose a less
-verbose level.
-
-## How can I delete the mock function's argument in an action? ##
-
-If you find yourself needing to perform some action that's not
-supported by Google Mock directly, remember that you can define your own
-actions using
-[MakeAction()](cook_book.md#writing-new-actions-quickly) or
-[MakePolymorphicAction()](cook_book.md#writing-new-polymorphic-actions),
-or you can write a stub function and invoke it using
-[Invoke()](cook_book.md#using-functionsmethodsfunctors-as-actions).
-
-## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ##
-
-What?! I think it's beautiful. :-)
-
-While which syntax looks more natural is a subjective matter to some
-extent, Google Mock's syntax was chosen for several practical advantages it
-has.
-
-Try to mock a function that takes a map as an argument:
-```cpp
-virtual int GetSize(const map<int, std::string>& m);
-```
-
-Using the proposed syntax, it would be:
-```cpp
-MOCK_METHOD1(GetSize, int, const map<int, std::string>& m);
-```
-
-Guess what? You'll get a compiler error as the compiler thinks that
-`const map<int, std::string>& m` are **two**, not one, arguments. To work
-around this you can use `typedef` to give the map type a name, but
-that gets in the way of your work. Google Mock's syntax avoids this
-problem as the function's argument types are protected inside a pair
-of parentheses:
-```cpp
-// This compiles fine.
-MOCK_METHOD1(GetSize, int(const map<int, std::string>& m));
-```
-
-You still need a `typedef` if the return type contains an unprotected
-comma, but that's much rarer.
-
-Other advantages include:
- 1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax.
- 1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it.
- 1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`!
-
-## My code calls a static/global function. Can I mock it? ##
-
-You can, but you need to make some changes.
-
-In general, if you find yourself needing to mock a static function,
-it's a sign that your modules are too tightly coupled (and less
-flexible, less reusable, less testable, etc). You are probably better
-off defining a small interface and call the function through that
-interface, which then can be easily mocked. It's a bit of work
-initially, but usually pays for itself quickly.
-
-This Google Testing Blog
-[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html)
-says it excellently. Check it out.
-
-## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ##
-
-I know it's not a question, but you get an answer for free any way. :-)
-
-With Google Mock, you can create mocks in C++ easily. And people might be
-tempted to use them everywhere. Sometimes they work great, and
-sometimes you may find them, well, a pain to use. So, what's wrong in
-the latter case?
-
-When you write a test without using mocks, you exercise the code and
-assert that it returns the correct value or that the system is in an
-expected state. This is sometimes called "state-based testing".
-
-Mocks are great for what some call "interaction-based" testing:
-instead of checking the system state at the very end, mock objects
-verify that they are invoked the right way and report an error as soon
-as it arises, giving you a handle on the precise context in which the
-error was triggered. This is often more effective and economical to
-do than state-based testing.
-
-If you are doing state-based testing and using a test double just to
-simulate the real object, you are probably better off using a fake.
-Using a mock in this case causes pain, as it's not a strong point for
-mocks to perform complex actions. If you experience this and think
-that mocks suck, you are just not using the right tool for your
-problem. Or, you might be trying to solve the wrong problem. :-)
-
-## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ##
-
-By all means, NO! It's just an FYI.
-
-What it means is that you have a mock function, you haven't set any
-expectations on it (by Google Mock's rule this means that you are not
-interested in calls to this function and therefore it can be called
-any number of times), and it is called. That's OK - you didn't say
-it's not OK to call the function!
-
-What if you actually meant to disallow this function to be called, but
-forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While
-one can argue that it's the user's fault, Google Mock tries to be nice and
-prints you a note.
-
-So, when you see the message and believe that there shouldn't be any
-uninteresting calls, you should investigate what's going on. To make
-your life easier, Google Mock prints the function name and arguments
-when an uninteresting call is encountered.
-
-## I want to define a custom action. Should I use Invoke() or implement the action interface? ##
-
-Either way is fine - you want to choose the one that's more convenient
-for your circumstance.
-
-Usually, if your action is for a particular function type, defining it
-using `Invoke()` should be easier; if your action can be used in
-functions of different types (e.g. if you are defining
-`Return(value)`), `MakePolymorphicAction()` is
-easiest. Sometimes you want precise control on what types of
-functions the action can be used in, and implementing
-`ActionInterface` is the way to go here. See the implementation of
-`Return()` in `include/gmock/gmock-actions.h` for an example.
-
-## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ##
-
-You got this error as Google Mock has no idea what value it should return
-when the mock method is called. `SetArgPointee()` says what the
-side effect is, but doesn't say what the return value should be. You
-need `DoAll()` to chain a `SetArgPointee()` with a `Return()`.
-
-See this [recipe](cook_book.md#mocking-side-effects) for more details and an example.
-
-
-## My question is not in your FAQ! ##
-
-If you cannot find the answer to your question in this FAQ, there are
-some other resources you can use:
-
- 1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics),
- 1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.).
-
-Please note that creating an issue in the
-[issue tracker](https://github.com/google/googletest/issues) is _not_
-a good way to get your answer, as it is monitored infrequently by a
-very small number of people.
-
-When asking a question, it's helpful to provide as much of the
-following information as possible (people cannot help you if there's
-not enough information in your question):
-
- * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version),
- * your operating system,
- * the name and version of your compiler,
- * the complete command line flags you give to your compiler,
- * the complete compiler error messages (if the question is about compilation),
- * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
diff --git a/googlemock/docs/gmock_faq.md b/googlemock/docs/gmock_faq.md
new file mode 100644
index 00000000..27f0eb06
--- /dev/null
+++ b/googlemock/docs/gmock_faq.md
@@ -0,0 +1,392 @@
+## Legacy gMock FAQ {#GMockFaq}
+
+<!-- GOOGLETEST_CM0020 DO NOT DELETE -->
+
+### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem?
+
+In order for a method to be mocked, it must be *virtual*, unless you use the
+[high-perf dependency injection technique](#MockingNonVirtualMethods).
+
+### Can I mock a variadic function?
+
+You cannot mock a variadic function (i.e. a function taking ellipsis (`...`)
+arguments) directly in gMock.
+
+The problem is that in general, there is *no way* for a mock object to know how
+many arguments are passed to the variadic method, and what the arguments' types
+are. Only the *author of the base class* knows the protocol, and we cannot look
+into his or her head.
+
+Therefore, to mock such a function, the *user* must teach the mock object how to
+figure out the number of arguments and their types. One way to do it is to
+provide overloaded versions of the function.
+
+Ellipsis arguments are inherited from C and not really a C++ feature. They are
+unsafe to use and don't work with arguments that have constructors or
+destructors. Therefore we recommend to avoid them in C++ as much as possible.
+
+### MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why?
+
+If you compile this using Microsoft Visual C++ 2005 SP1:
+
+```cpp
+class Foo {
+ ...
+ virtual void Bar(const int i) = 0;
+};
+
+class MockFoo : public Foo {
+ ...
+ MOCK_METHOD(void, Bar, (const int i), (override));
+};
+```
+
+You may get the following warning:
+
+```shell
+warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
+```
+
+This is a MSVC bug. The same code compiles fine with gcc, for example. If you
+use Visual C++ 2008 SP1, you would get the warning:
+
+```shell
+warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
+```
+
+In C++, if you *declare* a function with a `const` parameter, the `const`
+modifier is ignored. Therefore, the `Foo` base class above is equivalent to:
+
+```cpp
+class Foo {
+ ...
+ virtual void Bar(int i) = 0; // int or const int? Makes no difference.
+};
+```
+
+In fact, you can *declare* `Bar()` with an `int` parameter, and define it with a
+`const int` parameter. The compiler will still match them up.
+
+Since making a parameter `const` is meaningless in the method declaration, we
+recommend to remove it in both `Foo` and `MockFoo`. That should workaround the
+VC bug.
+
+Note that we are talking about the *top-level* `const` modifier here. If the
+function parameter is passed by pointer or reference, declaring the pointee or
+referee as `const` is still meaningful. For example, the following two
+declarations are *not* equivalent:
+
+```cpp
+void Bar(int* p); // Neither p nor *p is const.
+void Bar(const int* p); // p is not const, but *p is.
+```
+
+### I can't figure out why gMock thinks my expectations are not satisfied. What should I do?
+
+You might want to run your test with `--gmock_verbose=info`. This flag lets
+gMock print a trace of every mock function call it receives. By studying the
+trace, you'll gain insights on why the expectations you set are not met.
+
+If you see the message "The mock function has no default action set, and its
+return type has no default value set.", then try
+[adding a default action](http://go/gmockguide#DefaultValue). Due to a known
+issue, unexpected calls on mocks without default actions don't print out a
+detailed comparison between the actual arguments and the expected arguments.
+
+### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug?
+
+gMock and `ScopedMockLog` are likely doing the right thing here.
+
+When a test crashes, the failure signal handler will try to log a lot of
+information (the stack trace, and the address map, for example). The messages
+are compounded if you have many threads with depth stacks. When `ScopedMockLog`
+intercepts these messages and finds that they don't match any expectations, it
+prints an error for each of them.
+
+You can learn to ignore the errors, or you can rewrite your expectations to make
+your test more robust, for example, by adding something like:
+
+```cpp
+using ::testing::AnyNumber;
+using ::testing::Not;
+...
+ // Ignores any log not done by us.
+ EXPECT_CALL(log, Log(_, Not(EndsWith("/my_file.cc")), _))
+ .Times(AnyNumber());
+```
+
+### How can I assert that a function is NEVER called?
+
+```cpp
+using ::testing::_;
+...
+ EXPECT_CALL(foo, Bar(_))
+ .Times(0);
+```
+
+### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant?
+
+When gMock detects a failure, it prints relevant information (the mock function
+arguments, the state of relevant expectations, and etc) to help the user debug.
+If another failure is detected, gMock will do the same, including printing the
+state of relevant expectations.
+
+Sometimes an expectation's state didn't change between two failures, and you'll
+see the same description of the state twice. They are however *not* redundant,
+as they refer to *different points in time*. The fact they are the same *is*
+interesting information.
+
+### I get a heapcheck failure when using a mock object, but using a real object is fine. What can be wrong?
+
+Does the class (hopefully a pure interface) you are mocking have a virtual
+destructor?
+
+Whenever you derive from a base class, make sure its destructor is virtual.
+Otherwise Bad Things will happen. Consider the following code:
+
+```cpp
+class Base {
+ public:
+ // Not virtual, but should be.
+ ~Base() { ... }
+ ...
+};
+
+class Derived : public Base {
+ public:
+ ...
+ private:
+ std::string value_;
+};
+
+...
+ Base* p = new Derived;
+ ...
+ delete p; // Surprise! ~Base() will be called, but ~Derived() will not
+ // - value_ is leaked.
+```
+
+By changing `~Base()` to virtual, `~Derived()` will be correctly called when
+`delete p` is executed, and the heap checker will be happy.
+
+### The "newer expectations override older ones" rule makes writing expectations awkward. Why does gMock do that?
+
+When people complain about this, often they are referring to code like:
+
+```cpp
+using ::testing::Return;
+...
+ // foo.Bar() should be called twice, return 1 the first time, and return
+ // 2 the second time. However, I have to write the expectations in the
+ // reverse order. This sucks big time!!!
+ EXPECT_CALL(foo, Bar())
+ .WillOnce(Return(2))
+ .RetiresOnSaturation();
+ EXPECT_CALL(foo, Bar())
+ .WillOnce(Return(1))
+ .RetiresOnSaturation();
+```
+
+The problem, is that they didn't pick the **best** way to express the test's
+intent.
+
+By default, expectations don't have to be matched in *any* particular order. If
+you want them to match in a certain order, you need to be explicit. This is
+gMock's (and jMock's) fundamental philosophy: it's easy to accidentally
+over-specify your tests, and we want to make it harder to do so.
+
+There are two better ways to write the test spec. You could either put the
+expectations in sequence:
+
+```cpp
+using ::testing::Return;
+...
+ // foo.Bar() should be called twice, return 1 the first time, and return
+ // 2 the second time. Using a sequence, we can write the expectations
+ // in their natural order.
+ {
+ InSequence s;
+ EXPECT_CALL(foo, Bar())
+ .WillOnce(Return(1))
+ .RetiresOnSaturation();
+ EXPECT_CALL(foo, Bar())
+ .WillOnce(Return(2))
+ .RetiresOnSaturation();
+ }
+```
+
+or you can put the sequence of actions in the same expectation:
+
+```cpp
+using ::testing::Return;
+...
+ // foo.Bar() should be called twice, return 1 the first time, and return
+ // 2 the second time.
+ EXPECT_CALL(foo, Bar())
+ .WillOnce(Return(1))
+ .WillOnce(Return(2))
+ .RetiresOnSaturation();
+```
+
+Back to the original questions: why does gMock search the expectations (and
+`ON_CALL`s) from back to front? Because this allows a user to set up a mock's
+behavior for the common case early (e.g. in the mock's constructor or the test
+fixture's set-up phase) and customize it with more specific rules later. If
+gMock searches from front to back, this very useful pattern won't be possible.
+
+### gMock prints a warning when a function without EXPECT_CALL is called, even if I have set its behavior using ON_CALL. Would it be reasonable not to show the warning in this case?
+
+When choosing between being neat and being safe, we lean toward the latter. So
+the answer is that we think it's better to show the warning.
+
+Often people write `ON_CALL`s in the mock object's constructor or `SetUp()`, as
+the default behavior rarely changes from test to test. Then in the test body
+they set the expectations, which are often different for each test. Having an
+`ON_CALL` in the set-up part of a test doesn't mean that the calls are expected.
+If there's no `EXPECT_CALL` and the method is called, it's possibly an error. If
+we quietly let the call go through without notifying the user, bugs may creep in
+unnoticed.
+
+If, however, you are sure that the calls are OK, you can write
+
+```cpp
+using ::testing::_;
+...
+ EXPECT_CALL(foo, Bar(_))
+ .WillRepeatedly(...);
+```
+
+instead of
+
+```cpp
+using ::testing::_;
+...
+ ON_CALL(foo, Bar(_))
+ .WillByDefault(...);
+```
+
+This tells gMock that you do expect the calls and no warning should be printed.
+
+Also, you can control the verbosity by specifying `--gmock_verbose=error`. Other
+values are `info` and `warning`. If you find the output too noisy when
+debugging, just choose a less verbose level.
+
+### How can I delete the mock function's argument in an action?
+
+If your mock function takes a pointer argument and you want to delete that
+argument, you can use testing::DeleteArg<N>() to delete the N'th (zero-indexed)
+argument:
+
+```cpp
+using ::testing::_;
+ ...
+ MOCK_METHOD(void, Bar, (X* x, const Y& y));
+ ...
+ EXPECT_CALL(mock_foo_, Bar(_, _))
+ .WillOnce(testing::DeleteArg<0>()));
+```
+
+### How can I perform an arbitrary action on a mock function's argument?
+
+If you find yourself needing to perform some action that's not supported by
+gMock directly, remember that you can define your own actions using
+[`MakeAction()`](#NewMonoActions) or
+[`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function
+and invoke it using [`Invoke()`](#FunctionsAsActions).
+
+```cpp
+using ::testing::_;
+using ::testing::Invoke;
+ ...
+ MOCK_METHOD(void, Bar, (X* p));
+ ...
+ EXPECT_CALL(mock_foo_, Bar(_))
+ .WillOnce(Invoke(MyAction(...)));
+```
+
+### My code calls a static/global function. Can I mock it?
+
+You can, but you need to make some changes.
+
+In general, if you find yourself needing to mock a static function, it's a sign
+that your modules are too tightly coupled (and less flexible, less reusable,
+less testable, etc). You are probably better off defining a small interface and
+call the function through that interface, which then can be easily mocked. It's
+a bit of work initially, but usually pays for itself quickly.
+
+This Google Testing Blog
+[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it
+excellently. Check it out.
+
+### My mock object needs to do complex stuff. It's a lot of pain to specify the actions. gMock sucks!
+
+I know it's not a question, but you get an answer for free any way. :-)
+
+With gMock, you can create mocks in C++ easily. And people might be tempted to
+use them everywhere. Sometimes they work great, and sometimes you may find them,
+well, a pain to use. So, what's wrong in the latter case?
+
+When you write a test without using mocks, you exercise the code and assert that
+it returns the correct value or that the system is in an expected state. This is
+sometimes called "state-based testing".
+
+Mocks are great for what some call "interaction-based" testing: instead of
+checking the system state at the very end, mock objects verify that they are
+invoked the right way and report an error as soon as it arises, giving you a
+handle on the precise context in which the error was triggered. This is often
+more effective and economical to do than state-based testing.
+
+If you are doing state-based testing and using a test double just to simulate
+the real object, you are probably better off using a fake. Using a mock in this
+case causes pain, as it's not a strong point for mocks to perform complex
+actions. If you experience this and think that mocks suck, you are just not
+using the right tool for your problem. Or, you might be trying to solve the
+wrong problem. :-)
+
+### I got a warning "Uninteresting function call encountered - default action taken.." Should I panic?
+
+By all means, NO! It's just an FYI. :-)
+
+What it means is that you have a mock function, you haven't set any expectations
+on it (by gMock's rule this means that you are not interested in calls to this
+function and therefore it can be called any number of times), and it is called.
+That's OK - you didn't say it's not OK to call the function!
+
+What if you actually meant to disallow this function to be called, but forgot to
+write `EXPECT_CALL(foo, Bar()).Times(0)`? While one can argue that it's the
+user's fault, gMock tries to be nice and prints you a note.
+
+So, when you see the message and believe that there shouldn't be any
+uninteresting calls, you should investigate what's going on. To make your life
+easier, gMock dumps the stack trace when an uninteresting call is encountered.
+From that you can figure out which mock function it is, and how it is called.
+
+### I want to define a custom action. Should I use Invoke() or implement the ActionInterface interface?
+
+Either way is fine - you want to choose the one that's more convenient for your
+circumstance.
+
+Usually, if your action is for a particular function type, defining it using
+`Invoke()` should be easier; if your action can be used in functions of
+different types (e.g. if you are defining `Return(*value*)`),
+`MakePolymorphicAction()` is easiest. Sometimes you want precise control on what
+types of functions the action can be used in, and implementing `ActionInterface`
+is the way to go here. See the implementation of `Return()` in
+`testing/base/public/gmock-actions.h` for an example.
+
+### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean?
+
+You got this error as gMock has no idea what value it should return when the
+mock method is called. `SetArgPointee()` says what the side effect is, but
+doesn't say what the return value should be. You need `DoAll()` to chain a
+`SetArgPointee()` with a `Return()` that provides a value appropriate to the API
+being mocked.
+
+See this [recipe](cook_book.md#mocking-side-effects) for more details and an
+example.
+
+### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do?
+
+We've noticed that when the `/clr` compiler flag is used, Visual C++ uses 5~6
+times as much memory when compiling a mock class. We suggest to avoid `/clr`
+when compiling native C++ mocks.