mirror of
https://github.com/google/googletest.git
synced 2024-12-27 10:11:03 +08:00
Merge pull request #3189 from ellert:gtest-help-test-GNU/kFreeBSD
PiperOrigin-RevId: 349349288
This commit is contained in:
commit
d72813110c
5
googlemock/docs/contribute.md
Normal file
5
googlemock/docs/contribute.md
Normal file
@ -0,0 +1,5 @@
|
||||
# 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.
|
1600
googlemock/docs/design.md
Normal file
1600
googlemock/docs/design.md
Normal file
File diff suppressed because it is too large
Load Diff
49
googlemock/docs/guide.md
Normal file
49
googlemock/docs/guide.md
Normal file
@ -0,0 +1,49 @@
|
||||
# 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.
|
127
googlemock/docs/index.md
Normal file
127
googlemock/docs/index.md
Normal file
@ -0,0 +1,127 @@
|
||||
# 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).
|
111
googlemock/docs/overview.md
Normal file
111
googlemock/docs/overview.md
Normal file
@ -0,0 +1,111 @@
|
||||
# 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
|
11
googlemock/docs/sitemap.md
Normal file
11
googlemock/docs/sitemap.md
Normal file
@ -0,0 +1,11 @@
|
||||
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)
|
4
googlemock/docs/under-construction-banner.md
Normal file
4
googlemock/docs/under-construction-banner.md
Normal file
@ -0,0 +1,4 @@
|
||||
**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:
|
17
googlemock/g3doc/includes/g3_BUILD_rule.md
Normal file
17
googlemock/g3doc/includes/g3_BUILD_rule.md
Normal file
@ -0,0 +1,17 @@
|
||||
## 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.
|
54
googlemock/g3doc/includes/g3_absl_status_matcher.md
Normal file
54
googlemock/g3doc/includes/g3_absl_status_matcher.md
Normal file
@ -0,0 +1,54 @@
|
||||
### 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.
|
3
googlemock/g3doc/includes/g3_callback_snippet.md
Normal file
3
googlemock/g3doc/includes/g3_callback_snippet.md
Normal file
@ -0,0 +1,3 @@
|
||||
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.
|
22
googlemock/g3doc/includes/g3_callbacks_as_matchers.md
Normal file
22
googlemock/g3doc/includes/g3_callbacks_as_matchers.md
Normal file
@ -0,0 +1,22 @@
|
||||
#### 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.
|
134
googlemock/g3doc/includes/g3_content.md
Normal file
134
googlemock/g3doc/includes/g3_content.md
Normal file
@ -0,0 +1,134 @@
|
||||
#### 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.
|
@ -0,0 +1,36 @@
|
||||
#### 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>
|
37
googlemock/g3doc/includes/g3_mock_a_stubby_server.md
Normal file
37
googlemock/g3doc/includes/g3_mock_a_stubby_server.md
Normal file
@ -0,0 +1,37 @@
|
||||
### 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.
|
95
googlemock/g3doc/includes/g3_mock_callbacks.md
Normal file
95
googlemock/g3doc/includes/g3_mock_callbacks.md
Normal file
@ -0,0 +1,95 @@
|
||||
#### 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.)
|
9
googlemock/g3doc/includes/g3_mock_multithreaded.md
Normal file
9
googlemock/g3doc/includes/g3_mock_multithreaded.md
Normal file
@ -0,0 +1,9 @@
|
||||
### 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).
|
148
googlemock/g3doc/includes/g3_proto_matchers.md
Normal file
148
googlemock/g3doc/includes/g3_proto_matchers.md
Normal file
@ -0,0 +1,148 @@
|
||||
### 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>
|
31
googlemock/g3doc/includes/g3_stubby_actions.md
Normal file
31
googlemock/g3doc/includes/g3_stubby_actions.md
Normal file
@ -0,0 +1,31 @@
|
||||
### 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>
|
185
googlemock/g3doc/includes/g3_testing_LOGs.md
Normal file
185
googlemock/g3doc/includes/g3_testing_LOGs.md
Normal file
@ -0,0 +1,185 @@
|
||||
#### 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.
|
77
googlemock/g3doc/includes/g3_testing_code_stubby_server.md
Normal file
77
googlemock/g3doc/includes/g3_testing_code_stubby_server.md
Normal file
@ -0,0 +1,77 @@
|
||||
#### 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.
|
109
googlemock/g3doc/includes/g3_useful_matchers_outsidegmock.md
Normal file
109
googlemock/g3doc/includes/g3_useful_matchers_outsidegmock.md
Normal file
@ -0,0 +1,109 @@
|
||||
### 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>
|
@ -0,0 +1,3 @@
|
||||
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/)*.
|
@ -1432,8 +1432,8 @@ given test suite, whether their definitions come before or *after* the
|
||||
|
||||
You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples.
|
||||
|
||||
[sample7_unittest.cc]: ../samples/sample7_unittest.cc "Parameterized Test example"
|
||||
[sample8_unittest.cc]: ../samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
|
||||
[sample7_unittest.cc]: ../googletest/samples/sample7_unittest.cc "Parameterized Test example"
|
||||
[sample8_unittest.cc]: ../googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
|
||||
|
||||
### Creating Value-Parameterized Abstract Tests
|
||||
|
||||
@ -1583,7 +1583,7 @@ TYPED_TEST(FooTest, HasPropertyA) { ... }
|
||||
|
||||
You can see [sample6_unittest.cc] for a complete example.
|
||||
|
||||
[sample6_unittest.cc]: ../samples/sample6_unittest.cc "Typed Test example"
|
||||
[sample6_unittest.cc]: ../googletest/samples/sample6_unittest.cc "Typed Test example"
|
||||
|
||||
## Type-Parameterized Tests
|
||||
|
||||
@ -2026,7 +2026,7 @@ You can do so by adding one line:
|
||||
Now, sit back and enjoy a completely different output from your tests. For more
|
||||
details, see [sample9_unittest.cc].
|
||||
|
||||
[sample9_unittest.cc]: ../samples/sample9_unittest.cc "Event listener example"
|
||||
[sample9_unittest.cc]: ../googletest/samples/sample9_unittest.cc "Event listener example"
|
||||
|
||||
You may append more than one listener to the list. When an `On*Start()` or
|
||||
`OnTestPartResult()` event is fired, the listeners will receive it in the order
|
||||
@ -2053,7 +2053,7 @@ by the former.
|
||||
|
||||
See [sample10_unittest.cc] for an example of a failure-raising listener.
|
||||
|
||||
[sample10_unittest.cc]: ../samples/sample10_unittest.cc "Failure-raising listener example"
|
||||
[sample10_unittest.cc]: ../googletest/samples/sample10_unittest.cc "Failure-raising listener example"
|
||||
|
||||
## Running Test Programs: Advanced Options
|
||||
|
||||
|
@ -281,7 +281,7 @@ If necessary, you can continue to derive test fixtures from a derived fixture.
|
||||
googletest has no limit on how deep the hierarchy can be.
|
||||
|
||||
For a complete example using derived test fixtures, see
|
||||
[sample5_unittest.cc](../samples/sample5_unittest.cc).
|
||||
[sample5_unittest.cc](../googletest/samples/sample5_unittest.cc).
|
||||
|
||||
## My compiler complains "void value not ignored as it ought to be." What does this mean?
|
||||
|
||||
|
@ -43,6 +43,7 @@ import gtest_test_utils
|
||||
|
||||
|
||||
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
|
||||
IS_GNUKFREEBSD = os.name == 'posix' and os.uname()[0] == 'GNU/kFreeBSD'
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
|
||||
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_')
|
||||
@ -111,7 +112,7 @@ class GTestHelpTest(gtest_test_utils.TestCase):
|
||||
self.assertEquals(0, exit_code)
|
||||
self.assert_(HELP_REGEX.search(output), output)
|
||||
|
||||
if IS_LINUX:
|
||||
if IS_LINUX or IS_GNUKFREEBSD:
|
||||
self.assert_(STREAM_RESULT_TO_FLAG in output, output)
|
||||
else:
|
||||
self.assert_(STREAM_RESULT_TO_FLAG not in output, output)
|
||||
|
Loading…
x
Reference in New Issue
Block a user