Googletest export
Move all docs into top-level docs/ directory PiperOrigin-RevId: 350211277
This commit is contained in:
parent
996b65e64e
commit
489283524e
@ -371,8 +371,8 @@ Verifies that `val1` is less than, or almost equal to, `val2`. You can replace
|
|||||||
|
|
||||||
### Asserting Using gMock Matchers
|
### Asserting Using gMock Matchers
|
||||||
|
|
||||||
[gMock](../../googlemock) comes with
|
[gMock](gmock_index.md) comes with
|
||||||
[a library of matchers](../../googlemock/docs/cheat_sheet.md#MatcherList) for
|
[a library of matchers](gmock_cheat_sheet.md#MatcherList) for
|
||||||
validating arguments passed to mock objects. A gMock *matcher* is basically a
|
validating arguments passed to mock objects. A gMock *matcher* is basically a
|
||||||
predicate that knows how to describe itself. It can be used in these assertion
|
predicate that knows how to describe itself. It can be used in these assertion
|
||||||
macros:
|
macros:
|
||||||
@ -396,13 +396,13 @@ using ::testing::StartsWith;
|
|||||||
```
|
```
|
||||||
|
|
||||||
Read this
|
Read this
|
||||||
[recipe](../../googlemock/docs/cook_book.md#using-matchers-in-googletest-assertions)
|
[recipe](gmock_cook_book.md#using-matchers-in-googletest-assertions)
|
||||||
in the gMock Cookbook for more details.
|
in the gMock Cookbook for more details.
|
||||||
|
|
||||||
gMock has a rich set of matchers. You can do many things googletest cannot do
|
gMock has a rich set of matchers. You can do many things googletest cannot do
|
||||||
alone with them. For a list of matchers gMock provides, read
|
alone with them. For a list of matchers gMock provides, read
|
||||||
[this](../../googlemock/docs/cook_book.md##using-matchers). It's easy to write
|
[this](gmock_cook_book.md##using-matchers). It's easy to write
|
||||||
your [own matchers](../../googlemock/docs/cook_book.md#NewMatchers) too.
|
your [own matchers](gmock_cook_book.md#NewMatchers) too.
|
||||||
|
|
||||||
gMock is bundled with googletest, so you don't need to add any build dependency
|
gMock is bundled with googletest, so you don't need to add any build dependency
|
||||||
in order to take advantage of this. Just include `"gmock/gmock.h"`
|
in order to take advantage of this. Just include `"gmock/gmock.h"`
|
||||||
@ -414,7 +414,7 @@ and you're ready to go.
|
|||||||
you haven't.)
|
you haven't.)
|
||||||
|
|
||||||
You can use the gMock
|
You can use the gMock
|
||||||
[string matchers](../../googlemock/docs/cheat_sheet.md#string-matchers) with
|
[string matchers](gmock_cheat_sheet.md#string-matchers) with
|
||||||
`EXPECT_THAT()` or `ASSERT_THAT()` to do more string comparison tricks
|
`EXPECT_THAT()` or `ASSERT_THAT()` to do more string comparison tricks
|
||||||
(sub-string, prefix, suffix, regular expression, and etc). For example,
|
(sub-string, prefix, suffix, regular expression, and etc). For example,
|
||||||
|
|
||||||
@ -915,7 +915,7 @@ handlers registered with `pthread_atfork(3)`.
|
|||||||
|
|
||||||
Note: If you want to put a series of test assertions in a subroutine to check
|
Note: If you want to put a series of test assertions in a subroutine to check
|
||||||
for a complex condition, consider using
|
for a complex condition, consider using
|
||||||
[a custom GMock matcher](../../googlemock/docs/cook_book.md#NewMatchers)
|
[a custom GMock matcher](gmock_cook_book.md#NewMatchers)
|
||||||
instead. This lets you provide a more readable error message in case of failure
|
instead. This lets you provide a more readable error message in case of failure
|
||||||
and avoid all of the issues described below.
|
and avoid all of the issues described below.
|
||||||
|
|
@ -179,7 +179,7 @@ Example usage:
|
|||||||
To customize the default action for a particular method of a specific mock
|
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()`,
|
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
|
but it is used for setting default behaviors (when you do not require that the
|
||||||
mock method is called). See [here](cook_book.md#UseOnCall) for a more detailed
|
mock method is called). See [here](gmock_cook_book.md#UseOnCall) for a more detailed
|
||||||
discussion.
|
discussion.
|
||||||
|
|
||||||
```cpp
|
```cpp
|
||||||
@ -477,7 +477,7 @@ You can make a matcher from one or more other matchers:
|
|||||||
| Matcher | Description |
|
| Matcher | Description |
|
||||||
| :---------------------- | :------------------------------------ |
|
| :---------------------- | :------------------------------------ |
|
||||||
| `MatcherCast<T>(m)` | casts matcher `m` to type `Matcher<T>`. |
|
| `MatcherCast<T>(m)` | casts matcher `m` to type `Matcher<T>`. |
|
||||||
| `SafeMatcherCast<T>(m)` | [safely casts](cook_book.md#casting-matchers) matcher `m` to type `Matcher<T>`. |
|
| `SafeMatcherCast<T>(m)` | [safely casts](gmock_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. |
|
| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. |
|
||||||
<!-- mdformat on -->
|
<!-- mdformat on -->
|
||||||
|
|
||||||
@ -774,7 +774,7 @@ class MockFunction<R(A1, ..., An)> {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
See this [recipe](cook_book.md#using-check-points) for one application of it.
|
See this [recipe](gmock_cook_book.md#using-check-points) for one application of it.
|
||||||
|
|
||||||
## Flags
|
## Flags
|
||||||
|
|
@ -3,7 +3,8 @@
|
|||||||
<!-- GOOGLETEST_CM0012 DO NOT DELETE -->
|
<!-- GOOGLETEST_CM0012 DO NOT DELETE -->
|
||||||
|
|
||||||
You can find recipes for using gMock here. If you haven't yet, please read
|
You can find recipes for using gMock here. If you haven't yet, please read
|
||||||
[the dummy guide](for_dummies.md) first to make sure you understand the basics.
|
[the dummy guide](gmock_for_dummies.md) first to make sure you understand the
|
||||||
|
basics.
|
||||||
|
|
||||||
**Note:** gMock lives in the `testing` name space. For readability, it is
|
**Note:** gMock lives in the `testing` name space. For readability, it is
|
||||||
recommended to write `using ::testing::Foo;` once in your file before using the
|
recommended to write `using ::testing::Foo;` once in your file before using the
|
||||||
@ -1141,11 +1142,11 @@ Hamcrest project, which adds `assertThat()` to JUnit.
|
|||||||
|
|
||||||
### Using Predicates as Matchers
|
### Using Predicates as Matchers
|
||||||
|
|
||||||
gMock provides a [built-in set](cheat_sheet.md#MatcherList) of matchers. In case
|
gMock provides a [built-in set](gmock_cheat_sheet.md#MatcherList) of matchers.
|
||||||
you find them lacking, you can use an arbitrary unary predicate function or
|
In case you find them lacking, you can use an arbitrary unary predicate function
|
||||||
functor as a matcher - as long as the predicate accepts a value of the type you
|
or functor as a matcher - as long as the predicate accepts a value of the type
|
||||||
want. You do this by wrapping the predicate inside the `Truly()` function, for
|
you want. You do this by wrapping the predicate inside the `Truly()` function,
|
||||||
example:
|
for example:
|
||||||
|
|
||||||
```cpp
|
```cpp
|
||||||
using ::testing::Truly;
|
using ::testing::Truly;
|
||||||
@ -1710,7 +1711,7 @@ the test should reflect our real intent, instead of being overly constraining.
|
|||||||
|
|
||||||
gMock allows you to impose an arbitrary DAG (directed acyclic graph) on the
|
gMock allows you to impose an arbitrary DAG (directed acyclic graph) on the
|
||||||
calls. One way to express the DAG is to use the
|
calls. One way to express the DAG is to use the
|
||||||
[After](cheat_sheet.md#AfterClause) clause of `EXPECT_CALL`.
|
[After](gmock_cheat_sheet.md#AfterClause) clause of `EXPECT_CALL`.
|
||||||
|
|
||||||
Another way is via the `InSequence()` clause (not the same as the `InSequence`
|
Another way is via the `InSequence()` clause (not the same as the `InSequence`
|
||||||
class), which we borrowed from jMock 2. It's less flexible than `After()`, but
|
class), which we borrowed from jMock 2. It's less flexible than `After()`, but
|
||||||
@ -3714,8 +3715,8 @@ A cardinality is used in `Times()` to tell gMock how many times you expect a
|
|||||||
call to occur. It doesn't have to be exact. For example, you can say
|
call to occur. It doesn't have to be exact. For example, you can say
|
||||||
`AtLeast(5)` or `Between(2, 4)`.
|
`AtLeast(5)` or `Between(2, 4)`.
|
||||||
|
|
||||||
If the [built-in set](cheat_sheet.md#CardinalityList) of cardinalities doesn't
|
If the [built-in set](gmock_cheat_sheet.md#CardinalityList) of cardinalities
|
||||||
suit you, you are free to define your own by implementing the following
|
doesn't suit you, you are free to define your own by implementing the following
|
||||||
interface (in namespace `testing`):
|
interface (in namespace `testing`):
|
||||||
|
|
||||||
```cpp
|
```cpp
|
@ -7,7 +7,7 @@
|
|||||||
### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem?
|
### 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
|
In order for a method to be mocked, it must be *virtual*, unless you use the
|
||||||
[high-perf dependency injection technique](cook_book.md#MockingNonVirtualMethods).
|
[high-perf dependency injection technique](gmock_cook_book.md#MockingNonVirtualMethods).
|
||||||
|
|
||||||
### Can I mock a variadic function?
|
### Can I mock a variadic function?
|
||||||
|
|
||||||
@ -93,9 +93,9 @@ 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
|
If you see the message "The mock function has no default action set, and its
|
||||||
return type has no default value set.", then try
|
return type has no default value set.", then try
|
||||||
[adding a default action](for_dummies.md#DefaultValue). Due to a known issue,
|
[adding a default action](gmock_for_dummies.md#DefaultValue). Due to a known
|
||||||
unexpected calls on mocks without default actions don't print out a detailed
|
issue, unexpected calls on mocks without default actions don't print out a
|
||||||
comparison between the actual arguments and the expected arguments.
|
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?
|
### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug?
|
||||||
|
|
||||||
@ -388,8 +388,8 @@ 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
|
`SetArgPointee()` with a `Return()` that provides a value appropriate to the API
|
||||||
being mocked.
|
being mocked.
|
||||||
|
|
||||||
See this [recipe](cook_book.md#mocking-side-effects) for more details and an
|
See this [recipe](gmock_cook_book.md#mocking-side-effects) for more details and
|
||||||
example.
|
an example.
|
||||||
|
|
||||||
### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do?
|
### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do?
|
||||||
|
|
@ -150,7 +150,7 @@ follow:
|
|||||||
|
|
||||||
* Derive a class `MockTurtle` from `Turtle`.
|
* Derive a class `MockTurtle` from `Turtle`.
|
||||||
* Take a *virtual* function of `Turtle` (while it's possible to
|
* Take a *virtual* function of `Turtle` (while it's possible to
|
||||||
[mock non-virtual methods using templates](cook_book.md#MockingNonVirtualMethods),
|
[mock non-virtual methods using templates](gmock_cook_book.md#MockingNonVirtualMethods),
|
||||||
it's much more involved).
|
it's much more involved).
|
||||||
* In the `public:` section of the child class, write `MOCK_METHOD();`
|
* In the `public:` section of the child class, write `MOCK_METHOD();`
|
||||||
* Now comes the fun part: you take the function signature, cut-and-paste it
|
* Now comes the fun part: you take the function signature, cut-and-paste it
|
||||||
@ -376,8 +376,8 @@ convenient way of saying "any value".
|
|||||||
In the above examples, `100` and `50` are also matchers; implicitly, they are
|
In the above examples, `100` and `50` are also matchers; implicitly, they are
|
||||||
the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be
|
the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be
|
||||||
equal (using `operator==`) to the matcher argument. There are many
|
equal (using `operator==`) to the matcher argument. There are many
|
||||||
[built-in matchers](cheat_sheet.md#MatcherList) for common types (as well as
|
[built-in matchers](gmock_cheat_sheet.md#MatcherList) for common types (as well
|
||||||
[custom matchers](cook_book.md#NewMatchers)); for example:
|
as [custom matchers](gmock_cook_book.md#NewMatchers)); for example:
|
||||||
|
|
||||||
```cpp
|
```cpp
|
||||||
using ::testing::Ge;
|
using ::testing::Ge;
|
||||||
@ -399,7 +399,7 @@ EXPECT_CALL(turtle, GoTo);
|
|||||||
This works for all non-overloaded methods; if a method is overloaded, you need
|
This works for all non-overloaded methods; if a method is overloaded, you need
|
||||||
to help gMock resolve which overload is expected by specifying the number of
|
to help gMock resolve which overload is expected by specifying the number of
|
||||||
arguments and possibly also the
|
arguments and possibly also the
|
||||||
[types of the arguments](cook_book.md#SelectOverload).
|
[types of the arguments](gmock_cook_book.md#SelectOverload).
|
||||||
|
|
||||||
### Cardinalities: How Many Times Will It Be Called?
|
### Cardinalities: How Many Times Will It Be Called?
|
||||||
|
|
||||||
@ -416,7 +416,7 @@ called.
|
|||||||
|
|
||||||
We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the
|
We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the
|
||||||
list of built-in cardinalities you can use, see
|
list of built-in cardinalities you can use, see
|
||||||
[here](cheat_sheet.md#CardinalityList).
|
[here](gmock_cheat_sheet.md#CardinalityList).
|
||||||
|
|
||||||
The `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer
|
The `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer
|
||||||
the cardinality for you.** The rules are easy to remember:
|
the cardinality for you.** The rules are easy to remember:
|
||||||
@ -485,7 +485,7 @@ the *default* action for the function every time (unless, of course, you have a
|
|||||||
|
|
||||||
What can we do inside `WillOnce()` besides `Return()`? You can return a
|
What can we do inside `WillOnce()` besides `Return()`? You can return a
|
||||||
reference using `ReturnRef(*variable*)`, or invoke a pre-defined function, among
|
reference using `ReturnRef(*variable*)`, or invoke a pre-defined function, among
|
||||||
[others](cook_book.md#using-actions).
|
[others](gmock_cook_book.md#using-actions).
|
||||||
|
|
||||||
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause
|
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause
|
||||||
only once, even though the action may be performed many times. Therefore you
|
only once, even though the action may be performed many times. Therefore you
|
||||||
@ -563,7 +563,7 @@ overloaded). This makes any calls to the method expected. This is not necessary
|
|||||||
for methods that are not mentioned at all (these are "uninteresting"), but is
|
for methods that are not mentioned at all (these are "uninteresting"), but is
|
||||||
useful for methods that have some expectations, but for which other calls are
|
useful for methods that have some expectations, but for which other calls are
|
||||||
ok. See
|
ok. See
|
||||||
[Understanding Uninteresting vs Unexpected Calls](cook_book.md#uninteresting-vs-unexpected).
|
[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected).
|
||||||
|
|
||||||
### Ordered vs Unordered Calls {#OrderedCalls}
|
### Ordered vs Unordered Calls {#OrderedCalls}
|
||||||
|
|
||||||
@ -600,7 +600,7 @@ order as written. If a call is made out-of-order, it will be an error.
|
|||||||
|
|
||||||
(What if you care about the relative order of some of the calls, but not all of
|
(What if you care about the relative order of some of the calls, but not all of
|
||||||
them? Can you specify an arbitrary partial order? The answer is ... yes! The
|
them? Can you specify an arbitrary partial order? The answer is ... yes! The
|
||||||
details can be found [here](cook_book.md#OrderedCalls).)
|
details can be found [here](gmock_cook_book.md#OrderedCalls).)
|
||||||
|
|
||||||
### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations}
|
### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations}
|
||||||
|
|
||||||
@ -699,4 +699,4 @@ For example, in some tests we may not care about how many times `GetX()` and
|
|||||||
In gMock, if you are not interested in a method, just don't say anything about
|
In gMock, if you are not interested in a method, just don't say anything about
|
||||||
it. If a call to this method occurs, you'll see a warning in the test output,
|
it. If a call to this method occurs, you'll see a warning in the test output,
|
||||||
but it won't be a failure. This is called "naggy" behavior; to change, see
|
but it won't be a failure. This is called "naggy" behavior; to change, see
|
||||||
[The Nice, the Strict, and the Naggy](cook_book.md#NiceStrictNaggy).
|
[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy).
|
@ -166,10 +166,11 @@ exp ::= simple_expression_in_Python_syntax
|
|||||||
|
|
||||||
## Code
|
## Code
|
||||||
|
|
||||||
You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py).
|
You can find the source code of Pump in
|
||||||
It is still very unpolished and lacks automated tests, although it has been
|
[googlemock/scripts/pump.py](../googlemock/scripts/pump.py). It is still very
|
||||||
successfully used many times. If you find a chance to use it in your project,
|
unpolished and lacks automated tests, although it has been successfully used
|
||||||
please let us know what you think! We also welcome help on improving Pump.
|
many times. If you find a chance to use it in your project, please let us know
|
||||||
|
what you think! We also welcome help on improving Pump.
|
||||||
|
|
||||||
## Real Examples
|
## Real Examples
|
||||||
|
|
4
googlemock/docs/README.md
Normal file
4
googlemock/docs/README.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Content Moved
|
||||||
|
|
||||||
|
We are working on updates to the GoogleTest documentation, which has moved to
|
||||||
|
the top-level [docs](../../docs) directory.
|
@ -1,5 +0,0 @@
|
|||||||
# How to Contribute
|
|
||||||
|
|
||||||
googletest development is Piper-First. Just create a regular Piper CL. When the
|
|
||||||
CL is accepted and submitted, it will make its way to OSS via regular releasing
|
|
||||||
process.
|
|
File diff suppressed because it is too large
Load Diff
@ -1,49 +0,0 @@
|
|||||||
# googletest gMock Users Guide
|
|
||||||
|
|
||||||
go/gmockguide
|
|
||||||
|
|
||||||
Welcome to googletest: Google's C++ testing and mocking framework. gMock is a
|
|
||||||
mocking part of googletest.
|
|
||||||
|
|
||||||
* [OSS Version](https://github.com/google/googletest)
|
|
||||||
* [Google3](http://google3/third_party/googletest/)
|
|
||||||
|
|
||||||
* If you are new to gMock, start with [*gMock for Dummies*](for_dummies.md) to
|
|
||||||
learn the basic usage.
|
|
||||||
|
|
||||||
* Read [gMock Cookbook](cook_book.md) to learn more advanced usage and useful
|
|
||||||
tips.
|
|
||||||
|
|
||||||
* For a quick reference, check out [gMock Cheat Sheet](cheat_sheet.md).
|
|
||||||
|
|
||||||
* If you have questions, search [gMock FAQ](#GMockFaq) and the gmock-users@
|
|
||||||
archive before sending them to gmock-users@.
|
|
||||||
|
|
||||||
<!-- GOOGLETEST_CM0035 DO NOT DELETE -->
|
|
||||||
|
|
||||||
<!--#include file="for_dummies.md"-->
|
|
||||||
|
|
||||||
#### Side Effects
|
|
||||||
|
|
||||||
<!-- mdformat off(github rendering does not support multiline tables) -->
|
|
||||||
| 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. |
|
|
||||||
<!-- mdformat on -->
|
|
||||||
|
|
||||||
* When compiling with exceptions in google3, it's not enough to specify
|
|
||||||
`-fexceptions` to copts in your cc_test target. That flag will not be
|
|
||||||
inherited by gmock, and various headers will be compiled both with and
|
|
||||||
without `-fexceptions` causing subtle bugs. Instead you must pass
|
|
||||||
`--copt=-fexceptions` to the blaze command so the flag gets passed to all
|
|
||||||
targets... but this is Google and we don't use exceptions so it shouldn't
|
|
||||||
really be an issue.
|
|
@ -1,127 +0,0 @@
|
|||||||
# googletest Home
|
|
||||||
|
|
||||||
go/gmock
|
|
||||||
|
|
||||||
Googletest is Google's C++ testing and mocking framework. Please note that there
|
|
||||||
are legacy names you may encounter "gUnit" and "gMock" - these names are now
|
|
||||||
merged into "googletest"
|
|
||||||
|
|
||||||
<!-- GOOGLETEST_CM0035 DO NOT DELETE -->
|
|
||||||
|
|
||||||
## Testimonials
|
|
||||||
|
|
||||||
> "I'm really enjoying trying it, and it's amazing to me how far you've taken
|
|
||||||
> this in C++. It's changed the way I program (and therefore changed my life ;),
|
|
||||||
> and one of my teams has adopted it for all/most tests (and I'm working on the
|
|
||||||
> other)." \
|
|
||||||
> -- *Derek Thomson*, Google Mountain View
|
|
||||||
|
|
||||||
<section></section>
|
|
||||||
|
|
||||||
> "I started using mocks with EasyMock in Java a few years ago and found them
|
|
||||||
> **invaluable** for making unit testing as painless and effective as possible.
|
|
||||||
> I'm very glad (and amazed) to see you've managed to create something similar
|
|
||||||
> for C++. It's making the transition much more pleasant." \
|
|
||||||
> -- *David Harkness*, Google Mountain View
|
|
||||||
|
|
||||||
<section></section>
|
|
||||||
|
|
||||||
> "I #included `gmock.h` and lived to tell the tale... Kept me from having to
|
|
||||||
> depend on `MockBigtable` thus far, which is **huge**." \
|
|
||||||
> -- *Matthew Simmons*, Google NYC
|
|
||||||
|
|
||||||
<section></section>
|
|
||||||
|
|
||||||
> "I like the approach of `EXPECT_CALL` much more than EasyMock's mock modes
|
|
||||||
> (record, replay). It's the best way to ensure the user will never forget to
|
|
||||||
> verify the expectations: do it automatically!" \
|
|
||||||
> -- *Tiago Silverira*, Google Brazil
|
|
||||||
|
|
||||||
<section></section>
|
|
||||||
|
|
||||||
> "It's by far the best mocking library for C++, by a long-shot." \
|
|
||||||
> -- *Joe Walnes*, co-creator of jMock, Google London
|
|
||||||
|
|
||||||
## Learning googletest mocking
|
|
||||||
|
|
||||||
Please see the [*googletest Users Guide*](guide.md) for the combined gMock
|
|
||||||
mocking documentation.
|
|
||||||
|
|
||||||
## Resources for Users
|
|
||||||
|
|
||||||
* More docs:
|
|
||||||
* [Interview with gMock's Creator](http://www.corp.google.com/eng/testing/codegreen/v10/gMock.htm)
|
|
||||||
on the
|
|
||||||
[Feb 2008](http://www.corp.google.com/eng/testing/codegreen/v10/index.htm)
|
|
||||||
issue of [Code Green](http://go/codegreen) - discusses gMock's history
|
|
||||||
and philosophy.
|
|
||||||
* "Mockers of the (C++) world, delight!": TotT
|
|
||||||
[episode 66](http://big.corp.google.com/~jmcmaster/testing/2007/12/episode-68-mockers-of-c-world-delight.html) -
|
|
||||||
quick intro on gMock's benefits and usage
|
|
||||||
* "Mock logs better than gold": TotT
|
|
||||||
[episode 76](http://big.corp.google.com/~jmcmaster/testing/2008/02/episode-76-mock-logs-better-than-gold_21.html) -
|
|
||||||
how to test LOGs using gMock
|
|
||||||
* "Testing legacy code gently": TotT
|
|
||||||
[episode 84](http://big.corp.google.com/~jmcmaster/testing/2008/04/episode-84-testing-legacy-code-gently.html) -
|
|
||||||
using mock callbacks to test legacy code without a big refactoring
|
|
||||||
* "Literate testing with matchers": TotT
|
|
||||||
[episode 135](http://big.corp.google.com/~jmcmaster/testing/2009/06/episode-135-literate-testing-with_08.html) -
|
|
||||||
using matchers to get readable test code and readable test messages
|
|
||||||
* "Making a perfect matcher": TotT
|
|
||||||
[episode 139](http://big.corp.google.com/~jmcmaster/testing/2009/07/episode-139-making-perfect-matcher.html) -
|
|
||||||
defining custom matchers easily
|
|
||||||
* Talks
|
|
||||||
* "Declarative C++ Testing Using DSLs" talk (6/4/2008):
|
|
||||||
[abstract](https://wiki.corp.google.com/twiki/bin/view/Main/WanTalks#Declarative_C_Testing_Using_DSLs),
|
|
||||||
[slides](http://wiki.corp.google.com/twiki/pub/Main/WanTalks/0806-declarative-cpp-testing.xul#Eva)
|
|
||||||
(requires Firefox) - gMock's design and implementation tricks
|
|
||||||
* "Mocks made easy in C++ and Java" talk (4/23/2008):
|
|
||||||
[slides](http://go/MockTalk),
|
|
||||||
[fish](http://fish.corp.google.com/talks/8729/)
|
|
||||||
* "C++ mocks made easy - an introduction to gMock" talk (1/22/2008)):
|
|
||||||
[slides](http://wiki.corp.google.com/twiki/pub/Main/WanTalks/0801-mv-gmock.xul#eva)
|
|
||||||
(requires Firefox),
|
|
||||||
[video](https://video.google.com/a/google.com/?AuthEventSource=SSO#/Play/contentId=bd07003d4193a646)
|
|
||||||
* "A preview to gMock" talk (6/28/2007):
|
|
||||||
[PowerPoint slides](http://wiki.corp.google.com/twiki/pub/Main/WanTalks/0706-beijing-gmock-preview.ppt)
|
|
||||||
* Tools
|
|
||||||
* `/google/src/head/depot/google3/third_party/googletest/googlemock/scripts/generator/gmock_gen.py
|
|
||||||
*your.h ClassNames*` generates mocks for the given base classes (if no
|
|
||||||
class name is given, all classes in the file are emitted).
|
|
||||||
* Mocks
|
|
||||||
* [mock-log.h](http://s/?fileprint=//depot/google3/testing/base/public/mock-log.h) -
|
|
||||||
a sample on using gMock to create a mock class
|
|
||||||
* [gmock-sample-mock-log.cc](http://s/?fileprint=//depot/google3/testing/base/internal/gmock-sample-mock-log.cc) -
|
|
||||||
a sample on using gMock to test LOG()s
|
|
||||||
* Folks
|
|
||||||
* Meet the
|
|
||||||
[users](http://piano.kir.corp.google.com:8080/lica/?e=use%3Agmock).
|
|
||||||
* `gmock-users` list:
|
|
||||||
[subscribe](https://groups.google.com/a/google.com/group/gmock-users/topics),
|
|
||||||
[archive](https://groups.google.com/a/google.com/group/gmock-users/topics),
|
|
||||||
[smile!](http://piano.kir.corp.google.com:8080/lica/?e=gmock-users) Send
|
|
||||||
questions here if you still need help after consulting the on-line docs.
|
|
||||||
* `gmock-announce` list:
|
|
||||||
[subscribe](https://groups.google.com/a/google.com/group/gmock-announce/topics)
|
|
||||||
to this instead of `gmock-users` if you are interested in announcements
|
|
||||||
only.
|
|
||||||
|
|
||||||
## Resources for Contributors
|
|
||||||
|
|
||||||
* [Dashboard](http://unittest.corp.google.com/project/gunit-gmock/)
|
|
||||||
* [*gMock Design*](design.md) (go/gmockdesign) - the design doc
|
|
||||||
* `c-mock-dev` list (deprecated) -
|
|
||||||
[old archive](https://mailman.corp.google.com/pipermail/c/c-mock-dev/),
|
|
||||||
[new archive](https://g.corp.google.com/group/c-mock-dev-archive)
|
|
||||||
* `opensource-gmock` list - discussions on the development of gMock:
|
|
||||||
[subscribe](https://groups.google.com/a/google.com/group/opensource-gmock/subscribe),
|
|
||||||
[archive](https://g.corp.google.com/group/opensource-gmock-archive),
|
|
||||||
[smile!](http://piano.kir.corp.google.com:8080/lica/?e=opensource-gmock)
|
|
||||||
|
|
||||||
## Acknowledgments
|
|
||||||
|
|
||||||
We'd like to thank the following people for their contribution to gMock: Piotr
|
|
||||||
Kaminski, Jeffrey Yasskin (who/jyasskin), Joe Walnes, Bradford Cross, Keith Ray,
|
|
||||||
Craig Silverstein, Matthew Simmons (who/simmonmt), Hal Burch (who/hburch), Russ
|
|
||||||
Rufer, Rushabh Doshi (who/rdoshi), Gene Volovich (who/genev), Mike Bland, Neal
|
|
||||||
Norwitz (who/nnorwitz), Mark Zuber, Vadim Berman (who/vadimb).
|
|
@ -1,111 +0,0 @@
|
|||||||
# GMock
|
|
||||||
|
|
||||||
<!-- GOOGLETEST_CM0035 DO NOT DELETE -->
|
|
||||||
|
|
||||||
## What is gMock?
|
|
||||||
|
|
||||||
gMock is Google's framework for creating and using C++ mock classes. It helps
|
|
||||||
you design better systems and write better tests. A mock object is an object
|
|
||||||
that you use in a test instead of a real object. A mock object implements the
|
|
||||||
same interface as a real object but lets you specify at run time how the object
|
|
||||||
will be used. When you write tests that use a mock, you define expectations
|
|
||||||
about how the mock's methods will be called. Your test then verifies how your
|
|
||||||
real code behaves when interacting with the mock. See the
|
|
||||||
[Mock Objects Best Practices Guide](http://go/mock-objects#mocks-stubs-fakes)
|
|
||||||
for a comparison of mocks with stubs, fakes, and other kinds of test doubles.
|
|
||||||
|
|
||||||
For example, gMock provides a simple syntax for declaring "I expect the
|
|
||||||
RetryQuery method on this mock object to be called three times in the course of
|
|
||||||
this test". Your test will fail if the expectation isn't met.
|
|
||||||
|
|
||||||
The gMock library provides a mock framework for C++ similar to jMock or
|
|
||||||
EasyMock[?](http://go/easymock-codelab) for Java. In gMock you use macros to
|
|
||||||
define methods for your mock objects and set expectations for those methods.
|
|
||||||
gMock runs on Linux, Windows, and Mac OS X.
|
|
||||||
|
|
||||||
## What is gMock good for?
|
|
||||||
|
|
||||||
Mocks in general are good for:
|
|
||||||
|
|
||||||
- prototyping and designing new code and APIs.
|
|
||||||
- removing unnecessary, expensive, or unreliable dependencies from your tests.
|
|
||||||
|
|
||||||
gMock in particular is good for writing quality C++ mocks. Without the help of a
|
|
||||||
mocking framework like gMock, good C++ mocks are hard to create.
|
|
||||||
|
|
||||||
## What is gMock NOT good for?
|
|
||||||
|
|
||||||
gMock is not good for testing the behavior of dependencies. The point of testing
|
|
||||||
with mocks is to test the classes that use the mocks, not the mocks themselves.
|
|
||||||
Objects that have working toy implementations are called fakes instead of mocks.
|
|
||||||
For example, you could use an in-memory file system to fake disk operations.
|
|
||||||
|
|
||||||
Mocks aren't useful for very simple classes like
|
|
||||||
[Dumb Data Objects](http://big.corp.google.com/~jmcmaster/testing/2011/04/episode-220-blast-from-tott-past-dont.html).
|
|
||||||
If it's more trouble to use a mock than the real class, just use the real class.
|
|
||||||
|
|
||||||
## Who uses gMock?
|
|
||||||
|
|
||||||
There are over 30K tests using gmock. Virtually every C++ test at Google that
|
|
||||||
needs a mock object uses gMock.
|
|
||||||
|
|
||||||
## Practical matters
|
|
||||||
|
|
||||||
gMock is bundled with [gUnit](/third_party/googletest/googletest/docs/). To use
|
|
||||||
gMock,
|
|
||||||
[include a dependency](/third_party/googletest/googletest/docs/howto_cpp#LinuxTarget)
|
|
||||||
on `//testing/base/public:gunit` in the BUILD rule for your mocks, and use the
|
|
||||||
following include statement in the file that defines your mock class:
|
|
||||||
|
|
||||||
```
|
|
||||||
#include "gmock/gmock.h"
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
|
||||||
--------------------------- | ------------------------------------------
|
|
||||||
**Implementation language** | C++
|
|
||||||
**Code location** | google3/third_party/googletest/googlemock/
|
|
||||||
**Build target** | //testing/base/public:gunit
|
|
||||||
|
|
||||||
## Best practices
|
|
||||||
|
|
||||||
Use [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) to
|
|
||||||
enable easy mocking. If you define dependencies as interfaces rather than
|
|
||||||
concrete classes, you can swap out the production version of a class for a mock
|
|
||||||
during testing.
|
|
||||||
|
|
||||||
You can also use gMock during the design phase for your system. By sketching
|
|
||||||
your architecture using mocks rather than full implementations, you can evolve
|
|
||||||
your design more quickly.
|
|
||||||
|
|
||||||
## History and evolution
|
|
||||||
|
|
||||||
In January 2007 Zhanyong Wan and the Testing Technology team met with
|
|
||||||
experienced C++ engineers to find out about C++ testing needs. The team learned
|
|
||||||
that creating mocks in C++ was a major pain point. They looked around for
|
|
||||||
existing frameworks but didn't find anything satisfactory. So Zhanyong Wan
|
|
||||||
tackled the problem of creating a usable C++ mocking framework.
|
|
||||||
|
|
||||||
C++ posed a unique problem for mocking: while
|
|
||||||
[reflection](http://en.wikipedia.org/wiki/Reflection_\(computer_programming\))
|
|
||||||
in Java and Python make it easy to generate a mock implementation of any
|
|
||||||
interface, C++ does not have reflection. Wan hit on macros as a way to simplify
|
|
||||||
mock writing in C++, and gMock was born.
|
|
||||||
|
|
||||||
## Who to contact
|
|
||||||
|
|
||||||
- g/gmock-users
|
|
||||||
- g/gmock-announce
|
|
||||||
|
|
||||||
## Additional resources
|
|
||||||
|
|
||||||
- [gMock](http://go/gmock) - homepage
|
|
||||||
- [GMock for Dummies](http://<!-- GOOGLETEST_CM0013 DO NOT DELETE -->) - gets you started with gMock
|
|
||||||
quickly
|
|
||||||
- [GMock Cookbook](http://<!-- GOOGLETEST_CM0012 DO NOT DELETE -->) - recipes for common scenarios; covers
|
|
||||||
advanced usage.
|
|
||||||
- [GMock Cheat Sheet](http://<!-- GOOGLETEST_CM0020 DO NOT DELETE -->) - a quick reference
|
|
||||||
- [GMock FAQ](http://<!-- GOOGLETEST_CM0021 DO NOT DELETE -->) - frequently asked questions
|
|
||||||
- [gUnit GDH page](http://go/gunit-overview)
|
|
||||||
- [gUnit User's Guide](http://goto.corp.google.com/gunit) - gets you started
|
|
||||||
with gUnit, which is closely related to gMock
|
|
@ -1,11 +0,0 @@
|
|||||||
Googletest Mocking (gMock)
|
|
||||||
|
|
||||||
* [Home](index.md)
|
|
||||||
* [Overview](overview.md)
|
|
||||||
* [User's Guide](guide.md)
|
|
||||||
* [gMock For Dummies](for_dummies.md)
|
|
||||||
* [gMock Cookbook](cook_book.md)
|
|
||||||
* [gMock Cheat Sheet](cheat_sheet.md)
|
|
||||||
* [Design](design.md)
|
|
||||||
* [How To Contribute](contribute.md)
|
|
||||||
* [gMock FAQ](gmock_faq.md)
|
|
@ -1,4 +0,0 @@
|
|||||||
**WARNING:** This document was recently migrated from
|
|
||||||
[Goowiki](http://wtf/goowiki) (b/35424903) and may still require additional
|
|
||||||
updates or formatting. You can still access the original document on Goowiki
|
|
||||||
until the cleanup is complete:
|
|
@ -1,17 +0,0 @@
|
|||||||
## BUILD Rule
|
|
||||||
|
|
||||||
Add *one* of the following to your `deps`:
|
|
||||||
|
|
||||||
```build
|
|
||||||
"//testing/base/public:gunit",
|
|
||||||
"//testing/base/public:gtest_main",
|
|
||||||
```
|
|
||||||
|
|
||||||
Add this to your `.cc` file:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
#include "gmock/gmock.h"
|
|
||||||
```
|
|
||||||
|
|
||||||
Unless noted, *all functions and classes* are defined in the `::testing`
|
|
||||||
namespace.
|
|
@ -1,54 +0,0 @@
|
|||||||
### absl::Status
|
|
||||||
|
|
||||||
In namespace `testing::status`:
|
|
||||||
|
|
||||||
<a name="table22"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `IsOk()` </td>
|
|
||||||
<td> `argument` is a `absl::Status` or `absl::StatusOr<T>` whose status is OK. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `IsOkAndHolds(m)` </td>
|
|
||||||
<td>
|
|
||||||
`argument` is an `absl::StatusOr<T>` whose status is OK and whose inner value matches matcher `m`.
|
|
||||||
See also [`ASSERT_OK_AND_ASSIGN`](http://google3/testing/base/public/gmock_utils/status-matchers.h?q=symbol:ASSERT_OK_AND_ASSIGN).
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `StatusHasPayload()` </td>
|
|
||||||
<td> `argument` is a `absl::Status` or `absl::StatusOr<T>` whose status is not OK and which has any payload. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `StatusHasPayload<ProtoType>()` </td>
|
|
||||||
<td> `argument` is a `absl::Status` or `absl::StatusOr<T>` whose status is not OK and which has a payload of type `ProtoType`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `StatusHasPayload<ProtoType>(m)` </td>
|
|
||||||
<td> `argument` is a `absl::Status` or `absl::StatusOr<T>` whose status is not OK and which has a payload of type `ProtoType` that matches `m`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `StatusIs(s, c, m)` </td>
|
|
||||||
<td> `argument` is a `absl::Status` or `absl::StatusOr<T>` where: the error space matches `s`, the status code matches `c`, and the error message matches `m`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `StatusIs(c, m)` </td>
|
|
||||||
<td> `argument` is a `absl::Status` or `absl::StatusOr<T>` where: the error space is canonical, the status code matches `c`, and the error message matches `m`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `StatusIs(c)` </td>
|
|
||||||
<td> `argument` is a `absl::Status` or `absl::StatusOr<T>` where: the error space is canonical, and the status code matches `c`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `CanonicalStatusIs(c, m)` </td>
|
|
||||||
<td> `argument` is a `absl::Status` or `absl::StatusOr<T>` where: the canonical status code matches `c`, and the error message matches `m`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `CanonicalStatusIs(c)` </td>
|
|
||||||
<td> `argument` is a `absl::Status` or `absl::StatusOr<T>` where: the canonical status code matches `c`. </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
The two- and one-argument version of StatusIs use util::GetErrorSpaceForEnum to
|
|
||||||
determine the error space. If the error code matcher is not an enum with an
|
|
||||||
associated ErrorSpace, then the canonical space will be used.
|
|
@ -1,3 +0,0 @@
|
|||||||
You can also use `google3` permanent callback as an action. Note that `Callback`
|
|
||||||
or member function must be wrapped with `Invoke()`, whereas lambdas and functors
|
|
||||||
will work by themselves.
|
|
@ -1,22 +0,0 @@
|
|||||||
#### Using Callbacks as Matchers
|
|
||||||
|
|
||||||
Callbacks are widely used in `google3`. Conceptually, a `ResultCallback1<bool,
|
|
||||||
T>` is just a predicate on argument of type `T`. Naturally, we sometimes would
|
|
||||||
want to use such a callback as a matcher.
|
|
||||||
|
|
||||||
gMock gives you two function templates in namespace `testing` to turn callbacks
|
|
||||||
into matchers.
|
|
||||||
|
|
||||||
The first is `Truly(callback)`. It matches `argument` iff
|
|
||||||
`callback->Run(argument)` returns `true`.
|
|
||||||
|
|
||||||
The second is `AddressSatisfies(callback)`, which matches `argument` whenever
|
|
||||||
`callback->Run(&argument)` returns `true`.
|
|
||||||
|
|
||||||
The callbacks used in `Truly()` and `AddressSatisfies()` must be permanent (e.g.
|
|
||||||
those returned by `NewPermanentCallback()`), or you'll get a run-time error. The
|
|
||||||
matcher takes ownership of the callback, so you don't need to worry about
|
|
||||||
deleting it.
|
|
||||||
|
|
||||||
For examples, see
|
|
||||||
google3/testing/base/internal/gmock_utils/callback-matchers_test.cc.
|
|
@ -1,134 +0,0 @@
|
|||||||
#### Mock(able) Files {#MockableFile}
|
|
||||||
|
|
||||||
Don't use Mockable Files except to simulate errors on File. For general testing
|
|
||||||
of File, see go/file-testing.
|
|
||||||
|
|
||||||
google3/file/testing/mockablefile/mockablefile.h defines a `MockableFile` class.
|
|
||||||
It wraps an arbitrary `File` object and makes its virtual methods "mockable",
|
|
||||||
meaning that by default they'll delegate to the underlying `File` while you have
|
|
||||||
the option to call `ON_CALL` or `EXPECT_CALL` to set expectations on them and/or
|
|
||||||
change their behavior. This gives you the best part of both a mock and a real
|
|
||||||
object:
|
|
||||||
|
|
||||||
* The methods all have a working, default implementation. This can greatly
|
|
||||||
reduce the amount of work needed to set up the mock object.
|
|
||||||
* By setting expectations on the methods using `EXPECT_CALL`, you can easily
|
|
||||||
test how your code uses the `File`.
|
|
||||||
* By changing the methods' behavior (using `ON_CALL`), you can easily simulate
|
|
||||||
file errors and thus test your error handling code.
|
|
||||||
|
|
||||||
`mockablefile.h` contains copious comments on the usage, and
|
|
||||||
[`mockablefile_test.cc`](http://google3/file/testing/mockablefile/mockablefile_test.cc)
|
|
||||||
in the same directory contains some complete examples. Here's one of them,
|
|
||||||
showing how to simulate `Write()` errors:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
#include "file/base/path.h"
|
|
||||||
#include "file/testing/mockablefile/mockablefile.h"
|
|
||||||
|
|
||||||
using ::file::testing::MockableFile;
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::DoDefault;
|
|
||||||
using ::testing::Return;
|
|
||||||
|
|
||||||
// This test demonstrates using MockableFile to test code that handles
|
|
||||||
// File operation errors. We want to test that WriteToFile() returns
|
|
||||||
// false when there is a Write() failure. It's hard to cause such an
|
|
||||||
// error using a real File object, but easy to make MockableFile
|
|
||||||
// simulate it.
|
|
||||||
TEST(SampleTest, SimulateFileError) {
|
|
||||||
// Creates a mockable_file object from a real File object. The real
|
|
||||||
// file is a local file in this example, but can also be any other
|
|
||||||
// type of File.
|
|
||||||
MockableFile* const mockable_file = new MockableFile(
|
|
||||||
File::Create(file::JoinPath(FLAGS_test_tmpdir, "/test"), "w"));
|
|
||||||
|
|
||||||
// Tells the mockable file to start failing from the second Write()
|
|
||||||
// operation on.
|
|
||||||
EXPECT_CALL(*mockable_file, Write)
|
|
||||||
// By default, calls are delegated to the real File object.
|
|
||||||
.WillOnce(DoDefault())
|
|
||||||
// Simulates a write error from the second time on.
|
|
||||||
.WillRepeatedly(Return(util::UnknownError("message")));
|
|
||||||
|
|
||||||
// Exercises the code we want to test, letting it talk to the
|
|
||||||
// MockableFile object instead of a real one.
|
|
||||||
EXPECT_FALSE(WriteToFile(mockable_file));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`mockablefile.h` also defines a `MockableFileSystem` class that allows you to
|
|
||||||
register mockable files in the file system under the `/mockable` mount point,
|
|
||||||
which can then be opened by your code by name. Since `MockableFile` can wrap
|
|
||||||
**any** type of file, this means you can inject **any** type of file into the
|
|
||||||
file system for testing. For example, `google3/file/memfile/memfile.h` defines a
|
|
||||||
convenient in-memory file type `MutableStringFile`. Now, you can wrap a
|
|
||||||
`MutableStringFile` in a `MockableFile` and inject it using `MockableFileSystem`
|
|
||||||
in order to test error handling of File operations that want to open a file
|
|
||||||
themselves.
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
#include "file/memfile/memfile.h" // you also need to depend on //file/memfile:memfile in your BUILD file
|
|
||||||
#include "file/testing/mockablefile/mockablefile.h"
|
|
||||||
|
|
||||||
using ::file::testing::MockableFile;
|
|
||||||
using ::file::testing::MockableFileSystem;
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::DoDefault;
|
|
||||||
using ::testing::Return;
|
|
||||||
|
|
||||||
// This test demonstrates registering a MockableFile with (a.k.a.
|
|
||||||
// injecting it into) the file system and opening it by name later.
|
|
||||||
// We want to test that WriteToFileByName() returns false when there
|
|
||||||
// is a Write() failure.
|
|
||||||
TEST(SampleTest, RegisterMockableFile) {
|
|
||||||
// Creates a mockable_file from a MutableStringFile.
|
|
||||||
MockableFile* const mockable_file = new MockableFile(
|
|
||||||
MutableStringFile("/foo/bar", new string,
|
|
||||||
TAKE_OWNERSHIP, DO_NOT_ALLOW_MMAP));
|
|
||||||
|
|
||||||
// Creates a mockable file system so that we can inject
|
|
||||||
// mockable_file into it.
|
|
||||||
MockableFileSystem fs;
|
|
||||||
|
|
||||||
// Injects mockable_file as "/mockable/foo/bar".
|
|
||||||
const string kPath = "/mockable/foo/bar";
|
|
||||||
EXPECT_CALL(fs, CreateFile(kPath, "w", _, _, _))
|
|
||||||
.WillOnce(Return(mockable_file));
|
|
||||||
|
|
||||||
// Tells the mockable file to start failing from the second Write()
|
|
||||||
// operation on.
|
|
||||||
EXPECT_CALL(*mockable_file, Write)
|
|
||||||
// By default, calls are delegated to the real File object.
|
|
||||||
.WillOnce(DoDefault())
|
|
||||||
// Simulates a write error from the second time on.
|
|
||||||
.WillRepeatedly(Return(util::error::UNKNOWN));
|
|
||||||
|
|
||||||
// Exercises the code we want to test, letting it talk to the
|
|
||||||
// MockableFile object instead of a real one.
|
|
||||||
EXPECT_FALSE(WriteToFileByName(kPath));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Mock Network System Calls
|
|
||||||
|
|
||||||
Gary Morain (gmorain@) implemented mock network system calls such that you can
|
|
||||||
use gMock to control their behavior when testing code that invokes network
|
|
||||||
system calls. You can find the code here:
|
|
||||||
|
|
||||||
* google3/net/util/network_system_call_interface.h - the interface.
|
|
||||||
* google3/net/util/network_system_call.h - the real implementation.
|
|
||||||
* google3/net/util/network_system_call_mock.h - the mock implementation.
|
|
||||||
* google3/net/util/network_system_call_unittest.cc - the unit test and demo.
|
|
||||||
|
|
||||||
#### Mock Bigtable
|
|
||||||
|
|
||||||
Please see the
|
|
||||||
[Svala](https://sites.google.com/a/google.com/te-zrh/tools--technologies/gmock-bigtable)
|
|
||||||
project for a gMock-based Bigtable implementation.
|
|
||||||
|
|
||||||
#### Add Yours Here
|
|
||||||
|
|
||||||
Don't be shy! If you've created a mock class using gMock and think it would be
|
|
||||||
useful to other Googlers, write an entry about it on this wiki page so that
|
|
||||||
people can learn about it.
|
|
@ -1,36 +0,0 @@
|
|||||||
#### Matching Protocol Buffers
|
|
||||||
|
|
||||||
Many Google APIs pass protocol buffers around. gMock provides some matchers for
|
|
||||||
protocol buffers. You can use them to specify that an argument must be equal (or
|
|
||||||
equivalent) to a given protocol buffer.
|
|
||||||
|
|
||||||
`EqualsProto(proto_buffer)` matches an argument iff it's equal to
|
|
||||||
`proto_buffer`, as determined by the `Equals()` method of the argument. The
|
|
||||||
argument must be a protocol buffer; pointers must be dereferenced.
|
|
||||||
|
|
||||||
Sometimes we want to test for equivalence instead of equality, i.e. we want to
|
|
||||||
use the `Equivalent()` method to compare two protocol buffers. For this we can
|
|
||||||
use `EquivToProto(proto_buffer)`.
|
|
||||||
|
|
||||||
It's worth noting that all of the matchers we mention here make a copy of
|
|
||||||
`proto_buffer`. This means that you can use a matcher even if the original
|
|
||||||
protocol buffer used for creating the matcher has been destroyed. Just one less
|
|
||||||
thing for you to worry about!
|
|
||||||
|
|
||||||
Note that `EqualsProto` and `EquivToProto` work for both proto1 and proto2. They
|
|
||||||
are declared in `gmock.h`, so you do not have to include other files. See
|
|
||||||
go/protomatchers for more proto buffer matching goodies.
|
|
||||||
|
|
||||||
In addition: One application of `Property()` is testing protocol buffers:
|
|
||||||
|
|
||||||
<a name="table1"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `Property(&MyProto::has_size, true)` </td>
|
|
||||||
<td> Matches `proto` where `proto.has_size()` returns `true`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `Property(&MyProto::size, Gt(5))` </td>
|
|
||||||
<td> Matches `proto` where `proto.size()` is greater than 5. </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
@ -1,37 +0,0 @@
|
|||||||
### I need to mock a Stubby server. Should I use gMock or the service mocker? {#GMockVsServiceMocker}
|
|
||||||
|
|
||||||
To quote PiotrKaminski, the author of the service mocker:
|
|
||||||
|
|
||||||
You can find an introduction to the service mocker
|
|
||||||
[here](http://go/stubby-codelab#test-client), and detailed documentation in
|
|
||||||
net/rpc/testing/public/servicemocker.h. As I'm the author of the framework my
|
|
||||||
opinion on it can hardly be objective, but here are the main advantages it has
|
|
||||||
over gMock when it comes to mocking Stubby services:
|
|
||||||
|
|
||||||
* Services are mocked dynamically so there's no need to manually write mock
|
|
||||||
service implementations.
|
|
||||||
* The client's calls go through a real Stubby channel, which will catch some
|
|
||||||
errors that calling a service implementation directly would miss.
|
|
||||||
* The service mocker is aware of sync/async client distinctions and common
|
|
||||||
Stubby threading strategies, and in general allows you to exert more control
|
|
||||||
over when the callback is made.
|
|
||||||
* The base syntax and semantics are very similar to gMock, but Stubby-specific
|
|
||||||
matchers and actions make the testing code more compact.
|
|
||||||
* A powerful expectation grouping mechanism allows expressing complicated
|
|
||||||
async call ordering constraints in a readable fashion.
|
|
||||||
* By the end of the week, there'll be built-in support for testing call
|
|
||||||
cancellation.
|
|
||||||
|
|
||||||
Some disadvantages:
|
|
||||||
|
|
||||||
* The service mocker documentation is not as good as gMock's.
|
|
||||||
* The error messages are probably not as good as gMock's either.
|
|
||||||
* You can only mock services, not arbitrary classes. Expectations do not
|
|
||||||
interact with gMock's.
|
|
||||||
* Slightly different expectation matching semantics in corner cases, which
|
|
||||||
could get confusing if you're using gMock as well.
|
|
||||||
|
|
||||||
In my biased opinion, if you only need to mock out Stubby services, you should
|
|
||||||
look at the service mocker first. If you need to mock out other classes too, and
|
|
||||||
especially if you need to express relationships between service and other
|
|
||||||
expectations, you're probably better off with gMock.
|
|
@ -1,95 +0,0 @@
|
|||||||
#### Mock Callbacks
|
|
||||||
|
|
||||||
Callbacks (`"base/callback.h"`) are widely used in `google3` to package data and
|
|
||||||
logic together. Sometimes you want to test how your code invokes callbacks (with
|
|
||||||
what arguments, how many times, in which order, and etc). This is a job cut out
|
|
||||||
for mock callbacks.
|
|
||||||
|
|
||||||
`"testing/base/public/mock-callback.h"` defines a class template to mock
|
|
||||||
callbacks. Given arbitrary types `R`, `T1`, ..., and `Tn`, class
|
|
||||||
**`MockCallback<R(T1, ..., Tn)>`** mocks a callback that takes arguments of type
|
|
||||||
`T1`, ..., and `Tn`, and returns type `R`, which can be `void`. This class is
|
|
||||||
derived from its corresponding abstract callback classed defined in
|
|
||||||
`"base/callback.h"`, for example:
|
|
||||||
|
|
||||||
* `MockCallback<void()>` inherits from `Closure`,
|
|
||||||
* `MockCallback<void(int, double)>` inherits from `Callback2<int, double>`,
|
|
||||||
* `MockCallback<int()>` derives from `ResultCallback<int>`, and
|
|
||||||
* `MockCallback<string(bool)>` derives from `ResultCallback1<string, bool>`.
|
|
||||||
|
|
||||||
Compared with the various classes in `"base/callback.h"`, the mock classes share
|
|
||||||
the same name and only differ in the template arguments, so you will never have
|
|
||||||
trouble remembering which is called what.
|
|
||||||
|
|
||||||
Like a real callback, a mock callback can be either *single-use* or *permanent*.
|
|
||||||
A single-use mock callback will delete itself when invoked. A permanent mock
|
|
||||||
callback will not and thus can be invoked many times - you have to make sure it
|
|
||||||
is deleted somehow.
|
|
||||||
|
|
||||||
Since a mock object verifies all expectations on its mock methods in the
|
|
||||||
destructor, please link with `//base:heapcheck` (it is already linked
|
|
||||||
automatically if you link with `//testing/base/public:gtest_main`) to make sure
|
|
||||||
all mock callbacks
|
|
||||||
|
|
||||||
are properly deleted.
|
|
||||||
|
|
||||||
`MockCallback<R(T1, ..., Tn)>` has a mock method `OnRun()` with the signature:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
R OnRun(T1, ..., Tn);
|
|
||||||
```
|
|
||||||
|
|
||||||
`OnRun()` will be called whenever the mock callback is invoked. Note that we
|
|
||||||
don't name it `Run()` to match the method in the base class, as doing so will
|
|
||||||
interfere with mocking single-use callbacks.
|
|
||||||
|
|
||||||
Finally, `"mock-callback.h"` is a header-only library, so just include it and
|
|
||||||
go. Here's a complete example on how you use it:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
#include "testing/base/public/mock-callback.h"
|
|
||||||
|
|
||||||
// 1. Import the necessary names from the testing name space.
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::MockCallback;
|
|
||||||
using ::testing::NotNull;
|
|
||||||
using ::testing::NewMockCallback;
|
|
||||||
using ::testing::NewPermanentMockCallback;
|
|
||||||
using ::testing::SetArgPointee;
|
|
||||||
|
|
||||||
TEST(FooTest, DoesBar) {
|
|
||||||
// 2. Create a single-use mock callback using NewMockCallback(), or
|
|
||||||
// a permanent mock callback using NewPermanentMockCallback().
|
|
||||||
MockCallback<string(int n, bool show_sign)>* show_int = NewMockCallback();
|
|
||||||
std::unique_ptr<MockCallback<void(int* count)> > get_count(
|
|
||||||
NewPermanentMockCallback());
|
|
||||||
|
|
||||||
// 3. Set expectations on the OnRun() method of the mock callbacks.
|
|
||||||
EXPECT_CALL(*show_int, OnRun(5, true))
|
|
||||||
.WillOnce(Return("+5"));
|
|
||||||
EXPECT_CALL(*get_count, OnRun(NotNull()))
|
|
||||||
.WillOnce(SetArgPointee<0>(1))
|
|
||||||
.WillOnce(SetArgPointee<0>(2));
|
|
||||||
|
|
||||||
// 4. Exercise code that uses the mock callbacks. The single-use
|
|
||||||
// mock callback show_int will be verified and deleted when it's
|
|
||||||
// called. Link with //base:heapcheck to make sure it is not
|
|
||||||
// leaked.
|
|
||||||
Foo(5, show_int, get_count.get());
|
|
||||||
// Foo()'s signature:
|
|
||||||
// void Foo(int n, ResultCallback2<string, int, bool>* show_int,
|
|
||||||
// Callback1<int*>* get_count);
|
|
||||||
|
|
||||||
// 5. The permanent mock callback will be verified and deleted here,
|
|
||||||
// thanks to the std::unique_ptr.
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Did you notice that you don't specify the types when calling `NewMockCallback()`
|
|
||||||
and `NewPermanentMockCallback()`? Apparently they can read your mind and know
|
|
||||||
the type of the mock callback you want. :-)
|
|
||||||
|
|
||||||
(Seriously, these functions figure out their return types from the
|
|
||||||
left-hand-side of the assignment or the initialization, with the help of some
|
|
||||||
template tricks. But you don't need to understand how they work in order to use
|
|
||||||
mock callbacks.)
|
|
@ -1,9 +0,0 @@
|
|||||||
### Can I use gMock in multi-threaded programs?
|
|
||||||
|
|
||||||
googletest was designed with thread-safety in mind. It uses synchronization
|
|
||||||
primitives from `google3` to be thread-safe. If you work in `google3`, you can
|
|
||||||
use gMock in multiple threads safely. If you work outside of `google3` and need
|
|
||||||
gMock to be thread-safe, please let us know.
|
|
||||||
|
|
||||||
For more details on how to use gMock with threads, read this
|
|
||||||
[recipe](#UsingThreads).
|
|
@ -1,148 +0,0 @@
|
|||||||
### Protocol Buffer Matchers {#ProtoMatchers}
|
|
||||||
|
|
||||||
(go/protomatchers)
|
|
||||||
|
|
||||||
In the following, `argument` can be either a protocol buffer (version 1 or
|
|
||||||
version 2) or a pointer to it, and `proto` can be either a protocol buffer or a
|
|
||||||
human-readable ASCII string representing it (e.g. `"foo: 5"`). If you need help
|
|
||||||
writing the ASCII string, read go/textformat. "Fully-initialized" below means
|
|
||||||
all `required` fields are set.
|
|
||||||
|
|
||||||
<a name="table15"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `EqualsInitializedProto(proto)` </td>
|
|
||||||
<td> `argument` is fully-initialized and equal to `proto`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `EqualsProto(proto)` </td>
|
|
||||||
<td> `argument` is equal to `proto`. Can also be used as a multi-argument matcher; see below. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `EquivToInitializedProto(proto)` </td>
|
|
||||||
<td> `argument` is fully-initialized and equivalent to `proto`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `EquivToProto(proto)` </td>
|
|
||||||
<td> `argument` is equivalent to `proto`. Can also be used as a multi-argument matcher; see below. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `IsInitializedProto()` </td>
|
|
||||||
<td> `argument` is a fully-initialized protocol buffer. </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
Both Equiv and Equal matchers checks that two protocol buffers have identical
|
|
||||||
values, however only Equal matchers ensure that the protocol buffers fields were
|
|
||||||
set the same way (explicitly or through their default value).
|
|
||||||
|
|
||||||
When these matchers are given a string parameter, they *optionally* accept the
|
|
||||||
type of the protocol buffer as a template argument, e.g.
|
|
||||||
`EqualsProto<MyPB>("bar: 'xyz'")`.
|
|
||||||
|
|
||||||
The following *protocol buffer matcher transformers* in namespace
|
|
||||||
`::testing::proto` change the behavior of a matcher:
|
|
||||||
|
|
||||||
<a name="table16"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `Approximately(proto_matcher)` </td>
|
|
||||||
<td> The same as `proto_matcher` except that it compares floating-point fields approximately. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `Approximately(proto_matcher, margin)` </td>
|
|
||||||
<td> The same as `Approximately(proto_matcher)` except that two floating-point fields are considered equal if their absolute difference is <= `margin`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `Approximately(proto_matcher, margin, fraction)` </td>
|
|
||||||
<td> The same as `Approximately(proto_matcher)` except that two floating-point fields are considered equal if their absolute difference is <= `margin` or their fractional difference is <= `fraction`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `TreatingNaNsAsEqual(proto_matcher)` </td>
|
|
||||||
<td> The same as `proto_matcher` except that two floating-point fields are considered equal if both are NaN, matching the behavior of `NanSensitiveDoubleEq()`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `IgnoringRepeatedFieldOrdering(proto_matcher)` </td>
|
|
||||||
<td> The same as `proto_matcher` except that it ignores ordering of elements within repeated fields (see `proto2::MessageDifferencer::TreatAsSet()` for more details). </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `IgnoringFieldPaths({"some_field.subfield"}, proto_matcher)` </td>
|
|
||||||
<td> The same as `proto_matcher` except that it ignores the value of field `subfield` in field `some_field`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `Partially(proto_matcher)` </td>
|
|
||||||
<td> The same as `proto_matcher` except that only fields present in the expected protocol buffer are considered. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `WhenDeserialized(typed_proto_matcher)` </td>
|
|
||||||
<td> `argument` is a string in the protocol buffer binary format that can be deserialized to a protocol buffer matching `typed_proto_matcher`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `WhenDeserializedAs<PB>(matcher)` </td>
|
|
||||||
<td> `argument` is a string in the protocol buffer binary format that can be deserialized to a protocol buffer of type `PB` that matches `matcher`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `WhenParsedFromProtoText(typed_proto_matcher)` </td>
|
|
||||||
<td> `argument` is a string in the protocol buffer text format that can be parsed to a protocol buffer matching `typed_proto_matcher`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `WhenParsedFromProtoTextAs<PB>(matcher)` </td>
|
|
||||||
<td> `argument` is a string in the protocol buffer text format that can be parsed to a protocol buffer of type `PB` that matches `matcher`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `WhenUnpacked(typed_proto_matcher)` </td>
|
|
||||||
<td> `argument` is a `google.protobuf.Any` that can be unpacked into a protocol buffer of the type of `typed_proto_matcher` that matches that matcher. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `WhenUnpackedTo<PB>(matcher)` </td>
|
|
||||||
<td> `argument` is a `google.protobuf.Any` that can be unpacked into a protocol buffer of type `PB` that matches `matcher`. </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
where:
|
|
||||||
|
|
||||||
* `proto_matcher` can be any of the `Equals*` and `EquivTo*` protocol buffer
|
|
||||||
matchers above,
|
|
||||||
* `typed_proto_matcher` can be an `Equals*` or `EquivTo*` protocol buffer
|
|
||||||
matcher where the type of the expected protocol buffer is known at run time
|
|
||||||
(e.g. `EqualsProto(expected_pb)` or `EqualsProto<MyPB>("bar: 'xyz'")`).
|
|
||||||
* `matcher` can be any matcher that can be used to match a `PB` value, e.g.
|
|
||||||
`EqualsProto("bar: 'xyz'")`, `Not(EqualsProto(my_pb))`.
|
|
||||||
|
|
||||||
`Approximately()`, `Partially()`, and `TreatingNaNsAsEqual()` can be combined,
|
|
||||||
e.g. `Partially(Approximately(EqualsProto(foo)))`.
|
|
||||||
|
|
||||||
Note that `EqualsProto()` and `EquivToProto()` can be used as multi-argument
|
|
||||||
matchers that match a 2-tuple of protos. The following example shows how to
|
|
||||||
compare two vectors of protos.
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
vector<MyProto> actual;
|
|
||||||
vector<MyProto> expected;
|
|
||||||
... // Fill vectors with data
|
|
||||||
EXPECT_THAT(actual, Pointwise(EqualsProto(), expected));
|
|
||||||
```
|
|
||||||
|
|
||||||
Similarly, they can be used to compare a vector of protos against a vector of
|
|
||||||
strings.
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
vector<MyProto> actual;
|
|
||||||
... // Fill 'actual' with data
|
|
||||||
vector<string> expected {"foo:<bar:1>", "foo:<bar:2>"};
|
|
||||||
EXPECT_THAT(actual, Pointwise(EqualsProto(), expected));
|
|
||||||
// Or, concisely:
|
|
||||||
EXPECT_THAT(actual, Pointwise(EqualsProto(), {"foo:<bar:1>", "foo:<bar:2>"}));
|
|
||||||
```
|
|
||||||
|
|
||||||
<a name="table17"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `EqualsProto()` </td>
|
|
||||||
<td> `x.Equals(y)` </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `EquivToProto()` </td>
|
|
||||||
<td> `x.Equivalent(y)` </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
@ -1,31 +0,0 @@
|
|||||||
### Stubby Actions
|
|
||||||
|
|
||||||
gMock has the following actions to provide limited support for mocking Stubby
|
|
||||||
(go/stubby) services. You can use them to return a canned answer from a Stubby
|
|
||||||
call, which has the signature `void Method(RPC*, const Request*, Response*
|
|
||||||
response, Closure* done)`. You should consider using Service Mocker
|
|
||||||
(go/servicemocker) instead if your need is more complex.
|
|
||||||
|
|
||||||
<a name="table35"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `BeDone()` </td>
|
|
||||||
<td> Calls the `done` closure. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `FailWith(status)` </td>
|
|
||||||
<td> Fails the RPC with the given RPC status code. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `FailWithUtilStatus(util_status)` </td>
|
|
||||||
<td> Fails the RPC with the given util::Status error code. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `RespondWith(proto)` </td>
|
|
||||||
<td> Sets the `response` argument to the given protocol buffer, and calls the `done` closure. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `RespondWith(proto_string)` </td>
|
|
||||||
<td> Sets the `response` argument to the protocol buffer parsed from the given ASCII string, and calls the `done` closure. </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
@ -1,185 +0,0 @@
|
|||||||
#### Testing LOG()s {#TestingLogs}
|
|
||||||
|
|
||||||
LOG()s are widely used in `google3` programs. They make it possible to diagnose
|
|
||||||
a server crash when you don't have the luxury of reproducing the bug. They are
|
|
||||||
also great as a [tool for refactoring](http://go/log-pin).
|
|
||||||
|
|
||||||
Often we need to test how a piece of code calls LOG()s. Traditionally, this has
|
|
||||||
been done using [golden files](http://go/log-pin), which is tedious to set up
|
|
||||||
and brittle (what if a library you depend on starts to generate its own logs?).
|
|
||||||
The [`ScopedMemoryLog`](http://go/gunit-faq-scoped-mock-log) class was created
|
|
||||||
to allow writing robust LOG tests, but using it beyond the most basic scenario
|
|
||||||
can be awkward.
|
|
||||||
|
|
||||||
With gMock we have a better solution. `testing/base/public/mock-log.h` defines a
|
|
||||||
mock log sink class `ScopedMockLog`. A `ScopedMockLog` object intercepts all
|
|
||||||
LOG()s (except `LOG(FATAL)`) while it is alive. This object has a mock method of
|
|
||||||
this signature:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
void Log(LogSeverity severity, const string& path, const string& message);
|
|
||||||
```
|
|
||||||
|
|
||||||
This file comes with gUnit and gMock, so there is no need to add any dependency
|
|
||||||
to your `BUILD` rule in order to use it.
|
|
||||||
|
|
||||||
Here are some ideas on how to make use of it:
|
|
||||||
|
|
||||||
To test that the code generates exactly one warning message (and nothing else):
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::kDoNotCaptureLogsYet;
|
|
||||||
using ::testing::ScopedMockLog;
|
|
||||||
...
|
|
||||||
ScopedMockLog log(kDoNotCaptureLogsYet);
|
|
||||||
EXPECT_CALL(log, Log(WARNING, _, "Expected warning."));
|
|
||||||
log.StartCapturingLogs();
|
|
||||||
... code that LOG()s ...
|
|
||||||
```
|
|
||||||
|
|
||||||
To test that a particular message is logged exactly once (but there can be other
|
|
||||||
log messages with different contents):
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::kDoNotCaptureLogsYet;
|
|
||||||
using ::testing::AnyNumber;
|
|
||||||
using ::testing::ScopedMockLog;
|
|
||||||
...
|
|
||||||
ScopedMockLog log(kDoNotCaptureLogsYet);
|
|
||||||
EXPECT_CALL(log, Log).Times(AnyNumber());
|
|
||||||
EXPECT_CALL(log, Log(INFO, _, "Expected message"));
|
|
||||||
log.StartCapturingLogs();
|
|
||||||
... code that LOG()s ...
|
|
||||||
```
|
|
||||||
|
|
||||||
To test that no `ERROR` is logged (but there can be other log messages with
|
|
||||||
different severities):
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::kDoNotCaptureLogsYet;
|
|
||||||
using ::testing::AnyNumber;
|
|
||||||
using ::testing::ScopedMockLog;
|
|
||||||
...
|
|
||||||
ScopedMockLog log(kDoNotCaptureLogsYet);
|
|
||||||
EXPECT_CALL(log, Log).Times(AnyNumber());
|
|
||||||
EXPECT_CALL(log, Log(ERROR, _, _))
|
|
||||||
.Times(0);
|
|
||||||
log.StartCapturingLogs();
|
|
||||||
... code that LOG()s ...
|
|
||||||
```
|
|
||||||
|
|
||||||
To test that a particular message is logged at least once (and there can be
|
|
||||||
other log messages):
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::kDoNotCaptureLogsYet;
|
|
||||||
using ::testing::AnyNumber;
|
|
||||||
using ::testing::AtLeast;
|
|
||||||
using ::testing::ScopedMockLog;
|
|
||||||
...
|
|
||||||
ScopedMockLog log(kDoNotCaptureLogsYet);
|
|
||||||
EXPECT_CALL(log, Log).Times(AnyNumber());
|
|
||||||
EXPECT_CALL(log, Log(INFO, _, "Expected message"))
|
|
||||||
.Times(AtLeast(1));
|
|
||||||
log.StartCapturingLogs();
|
|
||||||
... code that LOG()s ...
|
|
||||||
```
|
|
||||||
|
|
||||||
To test that three LOG()s occur sequentially:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::kDoNotCaptureLogsYet;
|
|
||||||
using ::testing::InSequence;
|
|
||||||
using ::testing::ScopedMockLog;
|
|
||||||
...
|
|
||||||
ScopedMockLog log(kDoNotCaptureLogsYet);
|
|
||||||
{
|
|
||||||
InSequence s;
|
|
||||||
EXPECT_CALL(log, Log(INFO, _, "Log #1"));
|
|
||||||
EXPECT_CALL(log, Log(WARNING, _, "Log #2"));
|
|
||||||
EXPECT_CALL(log, Log(INFO, _, "Log #3"));
|
|
||||||
}
|
|
||||||
log.StartCapturingLogs();
|
|
||||||
... code that LOG()s ...
|
|
||||||
```
|
|
||||||
|
|
||||||
To test that the log message contains a certain sub-string:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::kDoNotCaptureLogsYet;
|
|
||||||
using ::testing::HasSubstr;
|
|
||||||
using ::testing::ScopedMockLog;
|
|
||||||
...
|
|
||||||
ScopedMockLog log(kDoNotCaptureLogsYet);
|
|
||||||
EXPECT_CALL(log, Log(WARNING, _, HasSubstr("needle")));
|
|
||||||
log.StartCapturingLogs();
|
|
||||||
... code that LOG()s ...
|
|
||||||
```
|
|
||||||
|
|
||||||
To test that a given module generates a specific log:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
using ::testing::kDoNotCaptureLogsYet;
|
|
||||||
using ::testing::ScopedMockLog;
|
|
||||||
...
|
|
||||||
ScopedMockLog log(kDoNotCaptureLogsYet);
|
|
||||||
EXPECT_CALL(log, Log(WARNING, "path/to/my_module.cc", "Expected warning."));
|
|
||||||
log.StartCapturingLogs();
|
|
||||||
... code that LOG()s ...
|
|
||||||
```
|
|
||||||
|
|
||||||
To test that code doesn't log anything at all:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::kDoNotCaptureLogsYet;
|
|
||||||
using ::testing::ScopedMockLog;
|
|
||||||
...
|
|
||||||
ScopedMockLog log(kDoNotCaptureLogsYet);
|
|
||||||
EXPECT_CALL(log, Log).Times(0);
|
|
||||||
log.StartCapturingLogs();
|
|
||||||
... code that does not LOG() ...
|
|
||||||
```
|
|
||||||
|
|
||||||
**Warning:** For robust tests, either ignore unexpected logs (loose), or ignore
|
|
||||||
logs in other modules (tight), otherwise your test may break if their logging
|
|
||||||
changes.
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::AnyNumber;
|
|
||||||
using ::testing::kDoNotCaptureLogsYet;
|
|
||||||
using ::testing::Not;
|
|
||||||
using ::testing::ScopedMockLog;
|
|
||||||
|
|
||||||
// ...
|
|
||||||
|
|
||||||
// Simple robust setup, ignores unexpected logs.
|
|
||||||
ScopedMockLog log(kDoNotCaptureLogsYet);
|
|
||||||
EXPECT_CALL(log, Log).Times(AnyNumber()); // Ignore unexpected logs.
|
|
||||||
EXPECT_CALL(log, Log(ERROR, "path/to/my_file.cc", _))
|
|
||||||
.Times(3); // Verifies logs from my_file.cc.
|
|
||||||
log.StartCapturingLogs();
|
|
||||||
// ... code that LOG()s ...
|
|
||||||
|
|
||||||
// ...
|
|
||||||
|
|
||||||
// Tighter alternative.
|
|
||||||
ScopedMockLog log(kDoNotCaptureLogsYet);
|
|
||||||
EXPECT_CALL(log, Log(_, Not("path/to/my_file.cc"), _))
|
|
||||||
.Times(AnyNumber()); // Ignores other modules.
|
|
||||||
EXPECT_CALL(log, Log(ERROR, "path/to/my_file.cc", _))
|
|
||||||
.Times(3); // Verifies logs from my_file.cc.
|
|
||||||
log.StartCapturingLogs();
|
|
||||||
// ... code that LOG()s ...
|
|
||||||
```
|
|
||||||
|
|
||||||
To test `LOG(DFATAL)`, use
|
|
||||||
[`EXPECT_DFATAL`](/third_party/googletest/googletest/docs/google3_faq#testing-death-in-debug-mode)
|
|
||||||
instead.
|
|
@ -1,77 +0,0 @@
|
|||||||
#### Testing Code that Uses a Stubby Server
|
|
||||||
|
|
||||||
(Contributed by JonWray on 2008/3/11; updated by ZhanyongWan later.)
|
|
||||||
|
|
||||||
I'm testing a C++ frontend that calls several different backends, but I'll just
|
|
||||||
include an example for one to keep this relatively short. This example is
|
|
||||||
mocking a `CacheServer` backend. An explanation follows the code.
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
using ::testing::_;
|
|
||||||
using ::testing::BeDone;
|
|
||||||
using ::testing::EqualsProto;
|
|
||||||
using ::testing::RespondWith;
|
|
||||||
|
|
||||||
class MockCacheServer : public CacheServerRPC {
|
|
||||||
public:
|
|
||||||
MockCacheServer(HTTPServer *hs) {
|
|
||||||
rpc2::EnableRPC2(this, rpc2::ServiceParameters());
|
|
||||||
CacheServerRPC::ExportService(hs);
|
|
||||||
ON_CALL(*this, Insert).WillByDefault(BeDone());
|
|
||||||
ON_CALL(*this, Lookup).WillByDefault(BeDone());
|
|
||||||
}
|
|
||||||
|
|
||||||
MOCK_METHOD(void, Insert,
|
|
||||||
(RPC*, const CacheInsertCommandProto*, CacheInsertResultsProto*,
|
|
||||||
Closure*),
|
|
||||||
(override));
|
|
||||||
MOCK_METHOD(void, Lookup,
|
|
||||||
(RPC*, const CacheLookupCommandProto*, CacheLookupResultsProto*,
|
|
||||||
Closure*),
|
|
||||||
(override));
|
|
||||||
};
|
|
||||||
...
|
|
||||||
// This is in the test fixture.
|
|
||||||
MockCacheServer cacheserver_;
|
|
||||||
...
|
|
||||||
// Now the code that uses it:
|
|
||||||
CacheLookupCommandProto command;
|
|
||||||
// Init command
|
|
||||||
CacheLookupResultsProto results;
|
|
||||||
// Init results
|
|
||||||
|
|
||||||
EXPECT_CALL(cacheserver_, Lookup(_, EqualsProto(command), _, _))
|
|
||||||
.WillOnce(RespondWith(results));
|
|
||||||
```
|
|
||||||
|
|
||||||
In the success case, the command matches the `EXPECT_CALL`, so results is set
|
|
||||||
and the callback is called.
|
|
||||||
|
|
||||||
In the failure case, the command matches the default `ON_CALL`, the results are
|
|
||||||
not set, and the done closure is called (don't want the test to hang).
|
|
||||||
|
|
||||||
So it's a bit ugly, but given that I need to mock five backends, I think it's
|
|
||||||
better than doing this manually. The best part is the nicely formatted error
|
|
||||||
messages when the expected call is incorrect. Once all this scaffolding is in
|
|
||||||
place, it's easy to churn out test suites.
|
|
||||||
|
|
||||||
**Discussions:**
|
|
||||||
|
|
||||||
* ZhanyongWan: `StubbySimulator` by Mike Bland might also be useful:
|
|
||||||
google3/testing/lib/net/rpc/stubby_simulator.h.
|
|
||||||
* JonWray: This is turning a mock into a fake, isn't it? All requests are
|
|
||||||
accepted, and you can write logic to set the reply conditionally on the
|
|
||||||
request. The interesting thing is the logic moves from the mock class into
|
|
||||||
the test suite.
|
|
||||||
* MikeBland: It's sort of a Frankenstein, but it works well for my purposes.
|
|
||||||
It collaborates with a mock Stubby server, which sets the expectation and
|
|
||||||
does the actual intercepting of the args, and then gives you the freedom to
|
|
||||||
fiddle with the results while the RPC is conceptually "in flight". This is
|
|
||||||
especially handy for "pausing" the RPC and having it return a state other
|
|
||||||
than `RPC::OK`. This sort of approach to splitting RPC calls into separate
|
|
||||||
objects from ControlFlows was first explored in
|
|
||||||
[TotT Episode 46](http://tott/2007/06/episode-46-encapsulated-rpcs-or.html).
|
|
||||||
* PiotrKaminski: The [Service Mocker](http://go/servicemocker) is a gMock-like
|
|
||||||
framework that specializes in mocking Stubby services. It allows for small,
|
|
||||||
in-process tests, doesn't require manually writing a service mock, and can
|
|
||||||
deal with async clients, streaming and testing for cancellations.
|
|
@ -1,109 +0,0 @@
|
|||||||
### Useful Matchers Defined Outside of gMock
|
|
||||||
|
|
||||||
#### std::tuple
|
|
||||||
|
|
||||||
**deps:** `"//util/tuple:matchers"` <br>
|
|
||||||
`#include "util/tuple/matchers.h"` <br>
|
|
||||||
In namespace `util::tuple::testing`:
|
|
||||||
|
|
||||||
<a name="table21"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `Tuple(m0, m1, ..., mn)` </td>
|
|
||||||
<td> `argument` is a `std::tuple` const reference with `n + 1` elements, where the i-th element matches `std::get*(argument)` </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `FieldPairsAre(m0, m1, ..., mn)` </td>
|
|
||||||
<td> matches a pair (2-tuple) of tuples where matcher `mi` matches the i-th fields of the tuples; usually for use inside `Pointwise()` or `UnorderedPointwise()` </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
#### Web
|
|
||||||
|
|
||||||
**deps:** `"//webutil/url:test_utils"` <br>
|
|
||||||
`#include "webutil/url/test_utils.h"`
|
|
||||||
|
|
||||||
<a name="table23"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `webutil_url::testing::HasUrlArg(key)` </td>
|
|
||||||
<td> `argument` is a URL string that has a query argument whose name is `key`. E.g. `http://foo.com/bar?key=value` </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `webutil_url::testing::HasUrlArg(key, m)` </td>
|
|
||||||
<td> `argument` is a URL string that has a query argument whose name is `key` and whose value matches `m`. </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `webutil_url::testing::HasUrlPathParam(key)` </td>
|
|
||||||
<td> `argument` is a URL string that has a path parameter whose name is `key`. E.g. `http://foo.com/bar;key=value` </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td> `webutil_url::testing::HasUrlPathParam(key, m)` </td>
|
|
||||||
<td> `argument` is a URL string that has a path parameter whose name is `key` and whose value matches `m`. </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
**deps:** `"//third_party/jsoncpp:testing"` <br>
|
|
||||||
`#include "third_party/jsoncpp/testing.h"`
|
|
||||||
|
|
||||||
<a name="table24"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `Json::testing::EqualsJson(json)` </td>
|
|
||||||
<td> `argument` is a string that represents the same Json value as the `json` string does. </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
#### Encoding
|
|
||||||
|
|
||||||
**deps:** `"//testing/lib/util/coding:varint"` <br>
|
|
||||||
`#include "testing/lib/util/coding/varint.h"`
|
|
||||||
|
|
||||||
<a name="table25"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `testing_lib_util_coding::EncodesVarint64(n)` </td>
|
|
||||||
<td> `argument` is a string that represents a Varint encoding of `n`, a `uint64` value. </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
#### XPath
|
|
||||||
|
|
||||||
**deps:** `"//template/prototemplate/testing:xpath_matcher"` <br>
|
|
||||||
`#include "template/prototemplate/testing/xpath_matcher.h"`
|
|
||||||
|
|
||||||
<a name="table26"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `prototemplate::testing::MatchesXPath(str)` </td>
|
|
||||||
<td> `argument` is a well-formed HTML/XML string that matches the given [XPath](http://www.w3.org/TR/xpath/#contents) expression. </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
#### Flume
|
|
||||||
|
|
||||||
**deps:** `"//pipeline/flume/contrib:matchers"` <br>
|
|
||||||
`#include "pipeline/flume/contrib/matchers.h"`
|
|
||||||
|
|
||||||
<a name="table27"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `flume::testing::Kv(key_matcher, value_matcher)` </td>
|
|
||||||
<td> `argument` is a `KV` where the key matches `key_matcher` and the value matches `value_matcher`. </td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
#### i18n strings
|
|
||||||
|
|
||||||
**deps:** `"///i18n/testing/public:expecti18n"` <br>
|
|
||||||
`#include "google3/i18n/testing/public/expecti18n.h"`
|
|
||||||
|
|
||||||
<a name="table28"></a>
|
|
||||||
<table border="1" cellspacing="0" cellpadding="1">
|
|
||||||
<tr>
|
|
||||||
<td> `i18n_testing::I18nEq(utf8)` </td>
|
|
||||||
<td> `argument` is a `absl::string_view` whose content matches `utf8` allowing for locale data changes.
|
|
||||||
In case it does not match, the error message contains both a readable version of both strings and the list of
|
|
||||||
decoded codepoints.</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
@ -1,3 +0,0 @@
|
|||||||
See also the [Wrap External APIs](http://go/d4tg/wrap-external.html) chapter of
|
|
||||||
the
|
|
||||||
*[Design for Testability Guide](http://www.corp.google.com/eng/howto/testing/testability_guide/)*.
|
|
4
googletest/docs/README.md
Normal file
4
googletest/docs/README.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Content Moved
|
||||||
|
|
||||||
|
We are working on updates to the GoogleTest documentation, which has moved to
|
||||||
|
the top-level [docs](../../docs) directory.
|
Loading…
x
Reference in New Issue
Block a user