Commit 48928352 authored by Abseil Team's avatar Abseil Team Committed by Derek Mauro
Browse files

Googletest export

Move all docs into top-level docs/ directory

PiperOrigin-RevId: 350211277
parent 996b65e6
### 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.
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.
#### 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.
#### 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.
#### 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>
### 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.
#### 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.)
### 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).
### 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>
### 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>
#### 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.
#### 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.
### 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>
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/)*.
# Content Moved
We are working on updates to the GoogleTest documentation, which has moved to
the top-level [docs](../../docs) directory.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment