Source release 19.5.0

This commit is contained in:
Cong Lin
2025-04-02 10:27:18 -07:00
parent 4407acee62
commit f7ec4fdeff
295 changed files with 32196 additions and 21748 deletions

View File

@@ -48,7 +48,7 @@
<div class="footer">
GoogleTest &middot;
<a href="https://github.com/google/googletest">GitHub Repository</a> &middot;
<a href="https://github.com/google/googletest/blob/master/LICENSE">License</a> &middot;
<a href="https://github.com/google/googletest/blob/main/LICENSE">License</a> &middot;
<a href="https://policies.google.com/privacy">Privacy Policy</a>
</div>
</div>

View File

@@ -1,9 +1,9 @@
# Advanced googletest Topics
# Advanced GoogleTest Topics
## Introduction
Now that you have read the [googletest Primer](primer.md) and learned how to
write tests using googletest, it's time to learn some new tricks. This document
Now that you have read the [GoogleTest Primer](primer.md) and learned how to
write tests using GoogleTest, it's time to learn some new tricks. This document
will show you more assertions as well as how to construct complex failure
messages, propagate fatal failures, reuse and speed up your test fixtures, and
use various flags with your tests.
@@ -25,7 +25,7 @@ Reference.
### Predicate Assertions for Better Error Messages
Even though googletest has a rich set of assertions, they can never be complete,
Even though GoogleTest has a rich set of assertions, they can never be complete,
as it's impossible (nor a good idea) to anticipate all scenarios a user might
run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a
complex expression, for lack of a better macro. This has the problem of not
@@ -35,7 +35,7 @@ failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
is awkward especially when the expression has side-effects or is expensive to
evaluate.
googletest gives you three different options to solve this problem:
GoogleTest gives you three different options to solve this problem:
#### Using an Existing Boolean Function
@@ -286,7 +286,7 @@ For example:
```c++
TEST(SkipTest, DoesSkip) {
GTEST_SKIP() << "Skipping single test";
EXPECT_EQ(0, 1); // Won't fail; it won't be executed
FAIL(); // Won't fail; it won't be executed
}
class SkipFixture : public ::testing::Test {
@@ -298,15 +298,15 @@ class SkipFixture : public ::testing::Test {
// Tests for SkipFixture won't be executed.
TEST_F(SkipFixture, SkipsOneTest) {
EXPECT_EQ(5, 7); // Won't fail
FAIL(); // Won't fail; it won't be executed
}
```
As with assertion macros, you can stream a custom message into `GTEST_SKIP()`.
## Teaching googletest How to Print Your Values
## Teaching GoogleTest How to Print Your Values
When a test assertion such as `EXPECT_EQ` fails, googletest prints the argument
When a test assertion such as `EXPECT_EQ` fails, GoogleTest prints the argument
values to help you debug. It does this using a user-extensible value printer.
This printer knows how to print built-in C++ types, native arrays, STL
@@ -315,73 +315,141 @@ prints the raw bytes in the value and hopes that you the user can figure it out.
As mentioned earlier, the printer is *extensible*. That means you can teach it
to do a better job at printing your particular type than to dump the bytes. To
do that, define `<<` for your type:
```c++
#include <ostream>
do that, define an `AbslStringify()` overload as a `friend` function template
for your type:
```cpp
namespace foo {
class Bar { // We want googletest to be able to print instances of this.
...
// Create a free inline friend function.
friend std::ostream& operator<<(std::ostream& os, const Bar& bar) {
return os << bar.DebugString(); // whatever needed to print bar to os
class Point { // We want GoogleTest to be able to print instances of this.
...
// Provide a friend overload.
template <typename Sink>
friend void AbslStringify(Sink& sink, const Point& point) {
absl::Format(&sink, "(%d, %d)", point.x, point.y);
}
int x;
int y;
};
// If you can't declare the function in the class it's important that the
// << operator is defined in the SAME namespace that defines Bar. C++'s look-up
// rules rely on that.
std::ostream& operator<<(std::ostream& os, const Bar& bar) {
return os << bar.DebugString(); // whatever needed to print bar to os
// AbslStringify overload is defined in the SAME namespace that defines Point.
// C++'s look-up rules rely on that.
enum class EnumWithStringify { kMany = 0, kChoices = 1 };
template <typename Sink>
void AbslStringify(Sink& sink, EnumWithStringify e) {
absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices");
}
} // namespace foo
```
Sometimes, this might not be an option: your team may consider it bad style to
have a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that
doesn't do what you want (and you cannot change it). If so, you can instead
define a `PrintTo()` function like this:
{: .callout .note}
Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its
string. For more information about supported operations on `AbslStringify()`'s
sink, see go/abslstringify.
`AbslStringify()` can also use `absl::StrFormat`'s catch-all `%v` type specifier
within its own format strings to perform type deduction. `Point` above could be
formatted as `"(%v, %v)"` for example, and deduce the `int` values as `%d`.
Sometimes, `AbslStringify()` might not be an option: your team may wish to print
types with extra debugging information for testing purposes only. If so, you can
instead define a `PrintTo()` function like this:
```c++
#include <ostream>
namespace foo {
class Bar {
class Point {
...
friend void PrintTo(const Bar& bar, std::ostream* os) {
*os << bar.DebugString(); // whatever needed to print bar to os
friend void PrintTo(const Point& point, std::ostream* os) {
*os << "(" << point.x << "," << point.y << ")";
}
int x;
int y;
};
// If you can't declare the function in the class it's important that PrintTo()
// is defined in the SAME namespace that defines Bar. C++'s look-up rules rely
// on that.
void PrintTo(const Bar& bar, std::ostream* os) {
*os << bar.DebugString(); // whatever needed to print bar to os
// is defined in the SAME namespace that defines Point. C++'s look-up rules
// rely on that.
void PrintTo(const Point& point, std::ostream* os) {
*os << "(" << point.x << "," << point.y << ")";
}
} // namespace foo
```
If you have defined both `<<` and `PrintTo()`, the latter will be used when
googletest is concerned. This allows you to customize how the value appears in
googletest's output without affecting code that relies on the behavior of its
`<<` operator.
If you have defined both `AbslStringify()` and `PrintTo()`, the latter will be
used by GoogleTest. This allows you to customize how the value appears in
GoogleTest's output without affecting code that relies on the behavior of
`AbslStringify()`.
If you want to print a value `x` using googletest's value printer yourself, just
If you have an existing `<<` operator and would like to define an
`AbslStringify()`, the latter will be used for GoogleTest printing.
If you want to print a value `x` using GoogleTest's value printer yourself, just
call `::testing::PrintToString(x)`, which returns an `std::string`:
```c++
vector<pair<Bar, int> > bar_ints = GetBarIntVector();
vector<pair<Point, int> > point_ints = GetPointIntVector();
EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
<< "bar_ints = " << testing::PrintToString(bar_ints);
EXPECT_TRUE(IsCorrectPointIntVector(point_ints))
<< "point_ints = " << testing::PrintToString(point_ints);
```
For more details regarding `AbslStringify()` and its integration with other
libraries, see go/abslstringify.
## Regular Expression Syntax
When built with Bazel and using Abseil, GoogleTest uses the
[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX
systems (Linux, Cygwin, Mac), GoogleTest uses the
[POSIX extended regular expression](https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
syntax. To learn about POSIX syntax, you may want to read this
[Wikipedia entry](https://en.wikipedia.org/wiki/Regular_expression#POSIX_extended).
On Windows, GoogleTest uses its own simple regular expression implementation. It
lacks many features. For example, we don't support union (`"x|y"`), grouping
(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among
others. Below is what we do support (`A` denotes a literal character, period
(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular
expressions.):
Expression | Meaning
---------- | --------------------------------------------------------------
`c` | matches any literal character `c`
`\\d` | matches any decimal digit
`\\D` | matches any character that's not a decimal digit
`\\f` | matches `\f`
`\\n` | matches `\n`
`\\r` | matches `\r`
`\\s` | matches any ASCII whitespace, including `\n`
`\\S` | matches any character that's not a whitespace
`\\t` | matches `\t`
`\\v` | matches `\v`
`\\w` | matches any letter, `_`, or decimal digit
`\\W` | matches any character that `\\w` doesn't match
`\\c` | matches any literal character `c`, which must be a punctuation
`.` | matches any single character except `\n`
`A?` | matches 0 or 1 occurrences of `A`
`A*` | matches 0 or many occurrences of `A`
`A+` | matches 1 or many occurrences of `A`
`^` | matches the beginning of a string (not that of each line)
`$` | matches the end of a string (not that of each line)
`xy` | matches `x` followed by `y`
To help you determine which capability is available on your system, GoogleTest
defines macros to govern which regular expression it is using. The macros are:
`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death
tests to work in all cases, you can either `#if` on these macros or use the more
limited syntax only.
## Death Tests
In many applications, there are assertions that can cause application failure if
@@ -393,7 +461,7 @@ corruption, security holes, or worse. Hence it is vitally important to test that
such assertion statements work as expected.
Since these precondition checks cause the processes to die, we call such tests
_death tests_. More generally, any test that checks that a program terminates
*death tests*. More generally, any test that checks that a program terminates
(except by throwing an exception) in an expected fashion is also a death test.
Note that if a piece of code throws an exception, we don't consider it "death"
@@ -439,6 +507,12 @@ verifies that:
exit with exit code 0, and
* calling `KillProcess()` kills the process with signal `SIGKILL`.
{: .callout .warning}
Warning: If your death test contains mocks and is expecting a specific exit
code, then you must allow the mock objects to be leaked via `Mock::AllowLeak`.
This is because the mock leak detector will exit with its own error code if it
detects a leak.
The test function body may contain other assertions and statements as well, if
necessary.
@@ -451,7 +525,7 @@ Note that a death test only cares about three things:
3. does the stderr output match `matcher`?
In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it
will **not** cause the death test to fail, as googletest assertions don't abort
will **not** cause the death test to fail, as GoogleTest assertions don't abort
the process.
### Death Test Naming
@@ -480,49 +554,6 @@ TEST_F(FooDeathTest, DoesThat) {
}
```
### Regular Expression Syntax
On POSIX systems (e.g. Linux, Cygwin, and Mac), googletest uses the
[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
syntax. To learn about this syntax, you may want to read this
[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
On Windows, googletest uses its own simple regular expression implementation. It
lacks many features. For example, we don't support union (`"x|y"`), grouping
(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among
others. Below is what we do support (`A` denotes a literal character, period
(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular
expressions.):
Expression | Meaning
---------- | --------------------------------------------------------------
`c` | matches any literal character `c`
`\\d` | matches any decimal digit
`\\D` | matches any character that's not a decimal digit
`\\f` | matches `\f`
`\\n` | matches `\n`
`\\r` | matches `\r`
`\\s` | matches any ASCII whitespace, including `\n`
`\\S` | matches any character that's not a whitespace
`\\t` | matches `\t`
`\\v` | matches `\v`
`\\w` | matches any letter, `_`, or decimal digit
`\\W` | matches any character that `\\w` doesn't match
`\\c` | matches any literal character `c`, which must be a punctuation
`.` | matches any single character except `\n`
`A?` | matches 0 or 1 occurrences of `A`
`A*` | matches 0 or many occurrences of `A`
`A+` | matches 1 or many occurrences of `A`
`^` | matches the beginning of a string (not that of each line)
`$` | matches the end of a string (not that of each line)
`xy` | matches `x` followed by `y`
To help you determine which capability is available on your system, googletest
defines macros to govern which regular expression it is using. The macros are:
`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death
tests to work in all cases, you can either `#if` on these macros or use the more
limited syntax only.
### How It Works
See [Death Assertions](reference/assertions.md#death) in the Assertions
@@ -537,7 +568,7 @@ arrange that kind of environment. For example, statically-initialized modules
may start threads before main is ever reached. Once threads have been created,
it may be difficult or impossible to clean them up.
googletest has three features intended to raise awareness of threading issues.
GoogleTest has three features intended to raise awareness of threading issues.
1. A warning is emitted if multiple threads are running when a death test is
encountered.
@@ -560,7 +591,7 @@ The automated testing framework does not set the style flag. You can choose a
particular style of death tests by setting the flag programmatically:
```c++
GTEST_FLAG_SET(death_test_style, "threadsafe")
GTEST_FLAG_SET(death_test_style, "threadsafe");
```
You can do this in `main()` to set the style for all death tests in the binary,
@@ -590,7 +621,7 @@ TEST(MyDeathTest, TestTwo) {
The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If
it leaves the current function via a `return` statement or by throwing an
exception, the death test is considered to have failed. Some googletest macros
exception, the death test is considered to have failed. Some GoogleTest macros
may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid
them in `statement`.
@@ -702,7 +733,7 @@ Some tips on using `SCOPED_TRACE`:
### Propagating Fatal Failures
A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that
when they fail they only abort the _current function_, not the entire test. For
when they fail they only abort the *current function*, not the entire test. For
example, the following test will segfault:
```c++
@@ -724,7 +755,7 @@ TEST(FooTest, Bar) {
}
```
To alleviate this, googletest provides three different solutions. You could use
To alleviate this, GoogleTest provides three different solutions. You could use
either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
`HasFatalFailure()` function. They are described in the following two
subsections.
@@ -758,7 +789,7 @@ in it, the test will continue after the subroutine returns. This may not be what
you want.
Often people want fatal failures to propagate like exceptions. For that
googletest offers the following macros:
GoogleTest offers the following macros:
Fatal assertion | Nonfatal assertion | Verifies
------------------------------------- | ------------------------------------- | --------
@@ -839,7 +870,7 @@ will output XML like this:
```xml
...
<testcase name="MinAndMaxWidgets" status="run" time="0.006" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" />
<testcase name="MinAndMaxWidgets" file="test.cpp" line="1" status="run" time="0.006" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" />
...
```
@@ -850,7 +881,7 @@ will output XML like this:
> needs to be prefixed with `::testing::Test::` if used outside of the
> `TEST` body and the test fixture class.
> * *`key`* must be a valid XML attribute name, and cannot conflict with the
> ones already used by googletest (`name`, `status`, `time`, `classname`,
> ones already used by GoogleTest (`name`, `status`, `time`, `classname`,
> `type_param`, and `value_param`).
> * Calling `RecordProperty()` outside of the lifespan of a test is allowed.
> If it's called outside of a test but between a test suite's
@@ -861,25 +892,25 @@ will output XML like this:
## Sharing Resources Between Tests in the Same Test Suite
googletest creates a new test fixture object for each test in order to make
GoogleTest creates a new test fixture object for each test in order to make
tests independent and easier to debug. However, sometimes tests use resources
that are expensive to set up, making the one-copy-per-test model prohibitively
expensive.
If the tests don't change the resource, there's no harm in their sharing a
single resource copy. So, in addition to per-test set-up/tear-down, googletest
single resource copy. So, in addition to per-test set-up/tear-down, GoogleTest
also supports per-test-suite set-up/tear-down. To use it:
1. In your test fixture class (say `FooTest` ), declare as `static` some member
variables to hold the shared resources.
2. Outside your test fixture class (typically just below it), define those
member variables, optionally giving them initial values.
3. In the same test fixture class, define a `static void SetUpTestSuite()`
function (remember not to spell it as **`SetupTestSuite`** with a small
`u`!) to set up the shared resources and a `static void TearDownTestSuite()`
function to tear them down.
3. In the same test fixture class, define a public member function `static void
SetUpTestSuite()` (remember not to spell it as **`SetupTestSuite`** with a
small `u`!) to set up the shared resources and a `static void
TearDownTestSuite()` function to tear them down.
That's it! googletest automatically calls `SetUpTestSuite()` before running the
That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the
*first test* in the `FooTest` test suite (i.e. before creating the first
`FooTest` object), and calls `TearDownTestSuite()` after running the *last test*
in it (i.e. after deleting the last `FooTest` object). In between, the tests can
@@ -894,7 +925,8 @@ Note that `SetUpTestSuite()` may be called multiple times for a test fixture
class that has derived classes, so you should not expect code in the function
body to be run only once. Also, derived classes still have access to shared
resources defined as static members, so careful consideration is needed when
managing shared resources to avoid memory leaks.
managing shared resources to avoid memory leaks if shared resources are not
properly cleaned up in `TearDownTestSuite()`.
Here's an example of per-test-suite set-up and tear-down:
@@ -905,10 +937,15 @@ class FooTest : public testing::Test {
// Called before the first test in this test suite.
// Can be omitted if not needed.
static void SetUpTestSuite() {
// Avoid reallocating static objects if called in subclasses of FooTest.
if (shared_resource_ == nullptr) {
shared_resource_ = new ...;
}
shared_resource_ = new ...;
// If `shared_resource_` is **not deleted** in `TearDownTestSuite()`,
// reallocation should be prevented because `SetUpTestSuite()` may be called
// in subclasses of FooTest and lead to memory leak.
//
// if (shared_resource_ == nullptr) {
// shared_resource_ = new ...;
// }
}
// Per-test-suite tear-down.
@@ -966,24 +1003,34 @@ class Environment : public ::testing::Environment {
};
```
Then, you register an instance of your environment class with googletest by
Then, you register an instance of your environment class with GoogleTest by
calling the `::testing::AddGlobalTestEnvironment()` function:
```c++
Environment* AddGlobalTestEnvironment(Environment* env);
```
Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of
each environment object, then runs the tests if none of the environments
reported fatal failures and `GTEST_SKIP()` was not called. `RUN_ALL_TESTS()`
always calls `TearDown()` with each environment object, regardless of whether or
not the tests were run.
Now, when `RUN_ALL_TESTS()` is invoked, it first calls the `SetUp()` method. The
tests are then executed, provided that none of the environments have reported
fatal failures and `GTEST_SKIP()` has not been invoked. Finally, `TearDown()` is
called.
Note that `SetUp()` and `TearDown()` are only invoked if there is at least one
test to be performed. Importantly, `TearDown()` is executed even if the test is
not run due to a fatal failure or `GTEST_SKIP()`.
Calling `SetUp()` and `TearDown()` for each iteration depends on the flag
`gtest_recreate_environments_when_repeating`. `SetUp()` and `TearDown()` are
called for each environment object when the object is recreated for each
iteration. However, if test environments are not recreated for each iteration,
`SetUp()` is called only on the first iteration, and `TearDown()` is called only
on the last iteration.
It's OK to register multiple environment objects. In this suite, their `SetUp()`
will be called in the order they are registered, and their `TearDown()` will be
called in the reverse order.
Note that googletest takes ownership of the registered environment objects.
Note that GoogleTest takes ownership of the registered environment objects.
Therefore **do not delete them** by yourself.
You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called,
@@ -1035,7 +1082,7 @@ they must be declared **public** rather than **protected** in order to use
```c++
class FooTest :
public testing::TestWithParam<const char*> {
public testing::TestWithParam<absl::string_view> {
// You can implement all the usual fixture class members here.
// To access the test parameter, call GetParam() from class
// TestWithParam<T>.
@@ -1046,7 +1093,7 @@ class BaseTest : public testing::Test {
...
};
class BarTest : public BaseTest,
public testing::WithParamInterface<const char*> {
public testing::WithParamInterface<absl::string_view> {
...
};
```
@@ -1093,6 +1140,11 @@ instantiation of the test suite. The next argument is the name of the test
pattern, and the last is the
[parameter generator](reference/testing.md#param-generators).
The parameter generator expression is not evaluated until GoogleTest is
initialized (via `InitGoogleTest()`). Any prior initialization done in the
`main` function will be accessible from the parameter generator, for example,
the results of flag parsing.
You can instantiate a test pattern more than once, so to distinguish different
instances of the pattern, the instantiation name is added as a prefix to the
actual test suite name. Remember to pick unique prefixes for different
@@ -1112,8 +1164,8 @@ with parameter values `"cat"` and `"dog"` using the
[`ValuesIn`](reference/testing.md#param-generators) parameter generator:
```c++
const char* pets[] = {"cat", "dog"};
INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(pets));
constexpr absl::string_view kPets[] = {"cat", "dog"};
INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets));
```
The tests from the instantiation above will have these names:
@@ -1140,8 +1192,8 @@ GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest);
You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples.
[sample7_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample7_unittest.cc "Parameterized Test example"
[sample8_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
[sample7_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc "Parameterized Test example"
[sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
### Creating Value-Parameterized Abstract Tests
@@ -1292,7 +1344,7 @@ TYPED_TEST(FooTest, HasPropertyA) { ... }
You can see [sample6_unittest.cc] for a complete example.
[sample6_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample6_unittest.cc "Typed Test example"
[sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example"
## Type-Parameterized Tests
@@ -1313,6 +1365,7 @@ First, define a fixture class template, as we did with typed tests:
```c++
template <typename T>
class FooTest : public testing::Test {
void DoSomethingInteresting();
...
};
```
@@ -1330,6 +1383,9 @@ this as many times as you want:
TYPED_TEST_P(FooTest, DoesBlah) {
// Inside a test, refer to TypeParam to get the type parameter.
TypeParam n = 0;
// You will need to use `this` explicitly to refer to fixture members.
this->DoSomethingInteresting()
...
}
@@ -1484,12 +1540,12 @@ To test them, we use the following special techniques:
## "Catching" Failures
If you are building a testing utility on top of googletest, you'll want to test
your utility. What framework would you use to test it? googletest, of course.
If you are building a testing utility on top of GoogleTest, you'll want to test
your utility. What framework would you use to test it? GoogleTest, of course.
The challenge is to verify that your testing utility reports failures correctly.
In frameworks that report a failure by throwing an exception, you could catch
the exception and assert on it. But googletest doesn't use exceptions, so how do
the exception and assert on it. But GoogleTest doesn't use exceptions, so how do
we test that a piece of code generates an expected failure?
`"gtest/gtest-spi.h"` contains some constructs to do this.
@@ -1632,9 +1688,9 @@ particular, you cannot find the test suite name in `SetUpTestSuite()`,
`TearDownTestSuite()` (where you know the test suite name implicitly), or
functions called from them.
## Extending googletest by Handling Test Events
## Extending GoogleTest by Handling Test Events
googletest provides an **event listener API** to let you receive notifications
GoogleTest provides an **event listener API** to let you receive notifications
about the progress of a test program and test failures. The events you can
listen to include the start and end of the test program, a test suite, or a test
method, among others. You may use this API to augment or replace the standard
@@ -1695,7 +1751,7 @@ Here's an example:
### Using Event Listeners
To use the event listener you have defined, add an instance of it to the
googletest event listener list (represented by class
GoogleTest event listener list (represented by class
[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s"
at the end of the name) in your `main()` function, before calling
`RUN_ALL_TESTS()`:
@@ -1706,7 +1762,7 @@ int main(int argc, char** argv) {
// Gets hold of the event listener list.
testing::TestEventListeners& listeners =
testing::UnitTest::GetInstance()->listeners();
// Adds a listener to the end. googletest takes the ownership.
// Adds a listener to the end. GoogleTest takes the ownership.
listeners.Append(new MinimalistPrinter);
return RUN_ALL_TESTS();
}
@@ -1727,7 +1783,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]: https://github.com/google/googletest/blob/master/googletest/samples/sample9_unittest.cc "Event listener example"
[sample9_unittest.cc]: https://github.com/google/googletest/blob/main/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
@@ -1754,17 +1810,17 @@ by the former.
See [sample10_unittest.cc] for an example of a failure-raising listener.
[sample10_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample10_unittest.cc "Failure-raising listener example"
[sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example"
## Running Test Programs: Advanced Options
googletest test programs are ordinary executables. Once built, you can run them
GoogleTest test programs are ordinary executables. Once built, you can run them
directly and affect their behavior via the following environment variables
and/or command line flags. For the flags to work, your programs must call
`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
To see a list of supported flags and their usage, please run your test program
with the `--help` flag. You can also use `-h`, `-?`, or `/?` for short.
with the `--help` flag.
If an option is specified both by an environment variable and by a flag, the
latter takes precedence.
@@ -1791,10 +1847,10 @@ corresponding environment variable for this flag.
#### Running a Subset of the Tests
By default, a googletest program runs all tests the user has defined. Sometimes,
By default, a GoogleTest program runs all tests the user has defined. Sometimes,
you want to run only a subset of the tests (e.g. for debugging or quickly
verifying a change). If you set the `GTEST_FILTER` environment variable or the
`--gtest_filter` flag to a filter string, googletest will only run the tests
`--gtest_filter` flag to a filter string, GoogleTest will only run the tests
whose full names (in the form of `TestSuiteName.TestName`) match the filter.
The format of a filter is a '`:`'-separated list of wildcard patterns (called
@@ -1825,7 +1881,7 @@ For example:
#### Stop test execution upon first failure
By default, a googletest program runs all tests the user has defined. In some
By default, a GoogleTest program runs all tests the user has defined. In some
cases (e.g. iterative test development & execution) it may be desirable stop
test execution upon first failure (trading improved latency for completeness).
If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set,
@@ -1842,7 +1898,7 @@ If you need to disable all tests in a test suite, you can either add `DISABLED_`
to the front of the name of each test, or alternatively add it to the front of
the test suite name.
For example, the following tests won't be run by googletest, even though they
For example, the following tests won't be run by GoogleTest, even though they
will still be compiled:
```c++
@@ -1857,7 +1913,7 @@ TEST_F(DISABLED_BarTest, DoesXyz) { ... }
{: .callout .note}
NOTE: This feature should only be used for temporary pain-relief. You still have
to fix the disabled tests at a later date. As a reminder, googletest will print
to fix the disabled tests at a later date. As a reminder, GoogleTest will print
a banner warning you if a test program contains any disabled tests.
{: .callout .tip}
@@ -1873,6 +1929,20 @@ the `--gtest_also_run_disabled_tests` flag or set the
You can combine this with the `--gtest_filter` flag to further select which
disabled tests to run.
### Enforcing Having At Least One Test Case
A not uncommon programmer mistake is to write a test program that has no test
case linked in. This can happen, for example, when you put test case definitions
in a library and the library is not marked as "always link".
To catch such mistakes, run the test program with the
`--gtest_fail_if_no_test_linked` flag or set the `GTEST_FAIL_IF_NO_TEST_LINKED`
environment variable to a value other than `0`. Now the program will fail if no
test case is linked in.
Note that *any* test case linked in makes the program valid for the purpose of
this check. In particular, even a disabled test case suffices.
### Repeating the Tests
Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it
@@ -1902,8 +1972,12 @@ Repeat the tests whose name matches the filter 1000 times.
If your test program contains
[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be
repeated in each iteration as well, as the flakiness may be in it. You can also
specify the repeat count by setting the `GTEST_REPEAT` environment variable.
repeated in each iteration as well, as the flakiness may be in it. To avoid
repeating global set-up/tear-down, specify
`--gtest_recreate_environments_when_repeating=false`{.nowrap}.
You can also specify the repeat count by setting the `GTEST_REPEAT` environment
variable.
### Shuffling the Tests
@@ -1911,16 +1985,16 @@ You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`
environment variable to `1`) to run the tests in a program in a random order.
This helps to reveal bad dependencies between tests.
By default, googletest uses a random seed calculated from the current time.
By default, GoogleTest uses a random seed calculated from the current time.
Therefore you'll get a different order every time. The console output includes
the random seed value, such that you can reproduce an order-related test failure
later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED`
flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an
integer in the range [0, 99999]. The seed value 0 is special: it tells
googletest to do the default behavior of calculating the seed from the current
GoogleTest to do the default behavior of calculating the seed from the current
time.
If you combine this with `--gtest_repeat=N`, googletest will pick a different
If you combine this with `--gtest_repeat=N`, GoogleTest will pick a different
random seed and re-shuffle the tests in each iteration.
### Distributing Test Functions to Multiple Machines
@@ -1979,7 +2053,7 @@ shards, but here's one possible scenario:
#### Colored Terminal Output
googletest can use colors in its terminal output to make it easier to spot the
GoogleTest can use colors in its terminal output to make it easier to spot the
important information:
<pre>...
@@ -2004,25 +2078,25 @@ important information:
You can set the `GTEST_COLOR` environment variable or the `--gtest_color`
command line flag to `yes`, `no`, or `auto` (the default) to enable colors,
disable colors, or let googletest decide. When the value is `auto`, googletest
disable colors, or let GoogleTest decide. When the value is `auto`, GoogleTest
will use colors if and only if the output goes to a terminal and (on non-Windows
platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`.
#### Suppressing test passes
By default, googletest prints 1 line of output for each test, indicating if it
By default, GoogleTest prints 1 line of output for each test, indicating if it
passed or failed. To show only test failures, run the test program with
`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`.
#### Suppressing the Elapsed Time
By default, googletest prints the time it takes to run each test. To disable
By default, GoogleTest prints the time it takes to run each test. To disable
that, run the test program with the `--gtest_print_time=0` command line flag, or
set the GTEST_PRINT_TIME environment variable to `0`.
#### Suppressing UTF-8 Text Output
In case of assertion failures, googletest prints expected and actual values of
In case of assertion failures, GoogleTest prints expected and actual values of
type `string` both as hex-encoded strings as well as in readable UTF-8 text if
they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8
text because, for example, you don't have an UTF-8 compatible output medium, run
@@ -2031,7 +2105,7 @@ environment variable to `0`.
#### Generating an XML Report
googletest can emit a detailed XML report to a file in addition to its normal
GoogleTest can emit a detailed XML report to a file in addition to its normal
textual output. The report contains the duration of each test, and thus can help
you identify slow tests.
@@ -2042,15 +2116,15 @@ in which case the output can be found in the `test_detail.xml` file in the
current directory.
If you specify a directory (for example, `"xml:output/directory/"` on Linux or
`"xml:output\directory\"` on Windows), googletest will create the XML file in
`"xml:output\directory\"` on Windows), GoogleTest will create the XML file in
that directory, named after the test executable (e.g. `foo_test.xml` for test
program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left
over from a previous run), googletest will pick a different name (e.g.
over from a previous run), GoogleTest will pick a different name (e.g.
`foo_test_1.xml`) to avoid overwriting it.
The report is based on the `junitreport` Ant task. Since that format was
originally intended for Java, a little interpretation is required to make it
apply to googletest tests, as shown here:
apply to GoogleTest tests, as shown here:
```xml
<testsuites name="AllTests" ...>
@@ -2065,8 +2139,8 @@ apply to googletest tests, as shown here:
```
* The root `<testsuites>` element corresponds to the entire test program.
* `<testsuite>` elements correspond to googletest test suites.
* `<testcase>` elements correspond to googletest test functions.
* `<testsuite>` elements correspond to GoogleTest test suites.
* `<testcase>` elements correspond to GoogleTest test functions.
For instance, the following program
@@ -2082,15 +2156,15 @@ could generate this report:
<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="3" failures="1" errors="0" time="0.035" timestamp="2011-10-31T18:52:42" name="AllTests">
<testsuite name="MathTest" tests="2" failures="1" errors="0" time="0.015">
<testcase name="Addition" status="run" time="0.007" classname="">
<testcase name="Addition" file="test.cpp" line="1" status="run" time="0.007" classname="">
<failure message="Value of: add(1, 1)&#x0A; Actual: 3&#x0A;Expected: 2" type="">...</failure>
<failure message="Value of: add(1, -1)&#x0A; Actual: 1&#x0A;Expected: 0" type="">...</failure>
</testcase>
<testcase name="Subtraction" status="run" time="0.005" classname="">
<testcase name="Subtraction" file="test.cpp" line="2" status="run" time="0.005" classname="">
</testcase>
</testsuite>
<testsuite name="LogicTest" tests="1" failures="0" errors="0" time="0.005">
<testcase name="NonContradiction" status="run" time="0.005" classname="">
<testcase name="NonContradiction" file="test.cpp" line="3" status="run" time="0.005" classname="">
</testcase>
</testsuite>
</testsuites>
@@ -2099,7 +2173,7 @@ could generate this report:
Things to note:
* The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how
many test functions the googletest program or test suite contains, while the
many test functions the GoogleTest program or test suite contains, while the
`failures` attribute tells how many of them failed.
* The `time` attribute expresses the duration of the test, test suite, or
@@ -2108,12 +2182,15 @@ Things to note:
* The `timestamp` attribute records the local date and time of the test
execution.
* Each `<failure>` element corresponds to a single failed googletest
* The `file` and `line` attributes record the source file location, where the
test was defined.
* Each `<failure>` element corresponds to a single failed GoogleTest
assertion.
#### Generating a JSON Report
googletest can also emit a JSON report as an alternative format to XML. To
GoogleTest can also emit a JSON report as an alternative format to XML. To
generate the JSON report, set the `GTEST_OUTPUT` environment variable or the
`--gtest_output` flag to the string `"json:path_to_output_file"`, which will
create the file at the given location. You can also just use the string
@@ -2124,7 +2201,7 @@ The report format conforms to the following JSON Schema:
```json
{
"$schema": "http://json-schema.org/schema#",
"$schema": "https://json-schema.org/schema#",
"type": "object",
"definitions": {
"TestCase": {
@@ -2147,6 +2224,8 @@ The report format conforms to the following JSON Schema:
"type": "object",
"properties": {
"name": { "type": "string" },
"file": { "type": "string" },
"line": { "type": "integer" },
"status": {
"type": "string",
"enum": ["RUN", "NOTRUN"]
@@ -2224,6 +2303,8 @@ message TestCase {
message TestInfo {
string name = 1;
string file = 6;
int32 line = 7;
enum Status {
RUN = 0;
NOTRUN = 1;
@@ -2267,6 +2348,8 @@ could generate this report:
"testsuite": [
{
"name": "Addition",
"file": "test.cpp",
"line": 1,
"status": "RUN",
"time": "0.007s",
"classname": "",
@@ -2283,6 +2366,8 @@ could generate this report:
},
{
"name": "Subtraction",
"file": "test.cpp",
"line": 2,
"status": "RUN",
"time": "0.005s",
"classname": ""
@@ -2298,6 +2383,8 @@ could generate this report:
"testsuite": [
{
"name": "NonContradiction",
"file": "test.cpp",
"line": 3,
"status": "RUN",
"time": "0.005s",
"classname": ""
@@ -2315,7 +2402,7 @@ IMPORTANT: The exact format of the JSON document is subject to change.
#### Detecting Test Premature Exit
Google Test implements the _premature-exit-file_ protocol for test runners to
Google Test implements the *premature-exit-file* protocol for test runners to
catch any kind of unexpected exits of test programs. Upon start, Google Test
creates the file which will be automatically deleted after all work has been
finished. Then, the test runner can check if this file exists. In case the file
@@ -2328,7 +2415,7 @@ variable has been set.
When running test programs under a debugger, it's very convenient if the
debugger can catch an assertion failure and automatically drop into interactive
mode. googletest's *break-on-failure* mode supports this behavior.
mode. GoogleTest's *break-on-failure* mode supports this behavior.
To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value
other than `0`. Alternatively, you can use the `--gtest_break_on_failure`
@@ -2336,9 +2423,9 @@ command line flag.
#### Disabling Catching Test-Thrown Exceptions
googletest can be used either with or without exceptions enabled. If a test
GoogleTest can be used either with or without exceptions enabled. If a test
throws a C++ exception or (on Windows) a structured exception (SEH), by default
googletest catches it, reports it as a test failure, and continues with the next
GoogleTest catches it, reports it as a test failure, and continues with the next
test method. This maximizes the coverage of a test run. Also, on Windows an
uncaught exception will cause a pop-up window, so catching the exceptions allows
you to run the tests automatically.
@@ -2376,4 +2463,4 @@ void __tsan_on_report() {
```
After compiling your project with one of the sanitizers enabled, if a particular
test triggers a sanitizer error, googletest will report that it failed.
test triggers a sanitizer error, GoogleTest will report that it failed.

View File

@@ -1,9 +1,9 @@
# Googletest FAQ
# GoogleTest FAQ
## Why should test suite names and test names not contain underscore?
{: .callout .note}
Note: Googletest reserves underscore (`_`) for special purpose keywords, such as
Note: GoogleTest reserves underscore (`_`) for special-purpose keywords, such as
[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition
to the following rationale.
@@ -33,9 +33,9 @@ contains `_`?
`TestSuiteName_Bar__Test`, which is invalid.
So clearly `TestSuiteName` and `TestName` cannot start or end with `_`
(Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't
followed by an upper-case letter. But that's getting complicated. So for
simplicity we just say that it cannot start with `_`.).
(Actually, `TestSuiteName` can start with `_`as long as the `_` isn't followed
by an upper-case letter. But that's getting complicated. So for simplicity we
just say that it cannot start with `_`.).
It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the
middle. However, consider this:
@@ -50,15 +50,15 @@ Now, the two `TEST`s will both generate the same class
So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and
`TestName`. The rule is more constraining than necessary, but it's simple and
easy to remember. It also gives googletest some wiggle room in case its
easy to remember. It also gives GoogleTest some wiggle room in case its
implementation needs to change in the future.
If you violate the rule, there may not be immediate consequences, but your test
may (just may) break with a new compiler (or a new version of the compiler you
are using) or with a new version of googletest. Therefore it's best to follow
are using) or with a new version of GoogleTest. Therefore it's best to follow
the rule.
## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
## Why does GoogleTest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
First of all, you can use `nullptr` with each of these macros, e.g.
`EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`,
@@ -68,7 +68,7 @@ because `nullptr` does not have the type problems that `NULL` does.
Due to some peculiarity of C++, it requires some non-trivial template meta
programming tricks to support using `NULL` as an argument of the `EXPECT_XX()`
and `ASSERT_XX()` macros. Therefore we only do it where it's most needed
(otherwise we make the implementation of googletest harder to maintain and more
(otherwise we make the implementation of GoogleTest harder to maintain and more
error-prone than necessary).
Historically, the `EXPECT_EQ()` macro took the *expected* value as its first
@@ -128,30 +128,9 @@ both approaches a try. Practice is a much better way to grasp the subtle
differences between the two tools. Once you have some concrete experience, you
can much more easily decide which one to use the next time.
## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!
{: .callout .note}
**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated*
now. Please use `EqualsProto`, etc instead.
`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and
are now less tolerant of invalid protocol buffer definitions. In particular, if
you have a `foo.proto` that doesn't fully qualify the type of a protocol message
it references (e.g. `message<Bar>` where it should be `message<blah.Bar>`), you
will now get run-time errors like:
```
... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto":
... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined.
```
If you see this, your `.proto` file is broken and needs to be fixed by making
the types fully qualified. The new definition of `ProtocolMessageEquals` and
`ProtocolMessageEquiv` just happen to reveal your bug.
## My death test modifies some state, but the change seems lost after the death test finishes. Why?
Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
Death tests (`EXPECT_DEATH`, etc.) are executed in a sub-process s.t. the
expected crash won't kill the test program (i.e. the parent process). As a
result, any in-memory side effects they incur are observable in their respective
sub-processes, but not in the parent process. You can think of them as running
@@ -162,7 +141,7 @@ methods, the parent process will think the calls have never occurred. Therefore,
you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH`
macro.
## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug?
## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a GoogleTest bug?
Actually, the bug is in `htonl()`.
@@ -192,16 +171,16 @@ class Foo {
};
```
You also need to define it *outside* of the class body in `foo.cc`:
you also need to define it *outside* of the class body in `foo.cc`:
```c++
const int Foo::kBar; // No initializer here.
```
Otherwise your code is **invalid C++**, and may break in unexpected ways. In
particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will
generate an "undefined reference" linker error. The fact that "it used to work"
doesn't mean it's valid. It just means that you were lucky. :-)
particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc.)
will generate an "undefined reference" linker error. The fact that "it used to
work" doesn't mean it's valid. It just means that you were lucky. :-)
If the declaration of the static data member is `constexpr` then it is
implicitly an `inline` definition, and a separate definition in `foo.cc` is not
@@ -225,7 +204,7 @@ cases may want to use the same or slightly different fixtures. For example, you
may want to make sure that all of a GUI library's test suites don't leak
important system resources like fonts and brushes.
In googletest, you share a fixture among test suites by putting the shared logic
In GoogleTest, you share a fixture among test suites by putting the shared logic
in a base test fixture, then deriving from that base a separate fixture for each
test suite that wants to use this common logic. You then use `TEST_F()` to write
tests using each derived fixture.
@@ -264,10 +243,10 @@ TEST_F(FooTest, Baz) { ... }
```
If necessary, you can continue to derive test fixtures from a derived fixture.
googletest has no limit on how deep the hierarchy can be.
GoogleTest has no limit on how deep the hierarchy can be.
For a complete example using derived test fixtures, see
[sample5_unittest.cc](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc).
[sample5_unittest.cc](https://github.com/google/googletest/blob/main/googletest/samples/sample5_unittest.cc).
## My compiler complains "void value not ignored as it ought to be." What does this mean?
@@ -278,7 +257,7 @@ disabled by our build system. Please see more details
## My death test hangs (or seg-faults). How do I fix it?
In googletest, death tests are run in a child process and the way they work is
In GoogleTest, death tests are run in a child process and the way they work is
delicate. To write death tests you really need to understand how they work—see
the details at [Death Assertions](reference/assertions.md#death) in the
Assertions Reference.
@@ -305,13 +284,13 @@ bullet - sorry!
## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}
The first thing to remember is that googletest does **not** reuse the same test
fixture object across multiple tests. For each `TEST_F`, googletest will create
The first thing to remember is that GoogleTest does **not** reuse the same test
fixture object across multiple tests. For each `TEST_F`, GoogleTest will create
a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
call `TearDown()`, and then delete the test fixture object.
When you need to write per-test set-up and tear-down logic, you have the choice
between using the test fixture constructor/destructor or `SetUp()/TearDown()`.
between using the test fixture constructor/destructor or `SetUp()`/`TearDown()`.
The former is usually preferred, as it has the following benefits:
* By initializing a member variable in the constructor, we have the option to
@@ -328,7 +307,7 @@ You may still want to use `SetUp()/TearDown()` in the following cases:
* C++ does not allow virtual function calls in constructors and destructors.
You can call a method declared as virtual, but it will not use dynamic
dispatch, it will use the definition from the class the constructor of which
dispatch. It will use the definition from the class the constructor of which
is currently executing. This is because calling a virtual method before the
derived class constructor has a chance to run is very dangerous - the
virtual method might operate on uninitialized data. Therefore, if you need
@@ -345,14 +324,14 @@ You may still want to use `SetUp()/TearDown()` in the following cases:
that many standard libraries (like STL) may throw when exceptions are
enabled in the compiler. Therefore you should prefer `TearDown()` if you
want to write portable tests that work with or without exceptions.
* The googletest team is considering making the assertion macros throw on
* The GoogleTest team is considering making the assertion macros throw on
platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux
client-side), which will eliminate the need for the user to propagate
failures from a subroutine to its caller. Therefore, you shouldn't use
googletest assertions in a destructor if your code could run on such a
GoogleTest assertions in a destructor if your code could run on such a
platform.
## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it?
## The compiler complains "no matching function to call" when I use `ASSERT_PRED*`. How do I fix it?
See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the
Assertions Reference.
@@ -375,7 +354,7 @@ they write
This is **wrong and dangerous**. The testing services needs to see the return
value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your
`main()` function ignores it, your test will be considered successful even if it
has a googletest assertion failure. Very bad.
has a GoogleTest assertion failure. Very bad.
We have decided to fix this (thanks to Michael Chastain for the idea). Now, your
code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with
@@ -410,7 +389,7 @@ C++ is case-sensitive. Did you spell it as `Setup()`?
Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and
wonder why it's never called.
## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious.
## I have several test suites which share the same test fixture logic; do I have to define a new test fixture class for each of them? This seems pretty tedious.
You don't have to. Instead of
@@ -440,14 +419,14 @@ TEST_F(BarTest, Abc) { ... }
TEST_F(BarTest, Def) { ... }
```
## googletest output is buried in a whole bunch of LOG messages. What do I do?
## GoogleTest output is buried in a whole bunch of LOG messages. What do I do?
The googletest output is meant to be a concise and human-friendly report. If
your test generates textual output itself, it will mix with the googletest
The GoogleTest output is meant to be a concise and human-friendly report. If
your test generates textual output itself, it will mix with the GoogleTest
output, making it hard to read. However, there is an easy solution to this
problem.
Since `LOG` messages go to stderr, we decided to let googletest output go to
Since `LOG` messages go to stderr, we decided to let GoogleTest output go to
stdout. This way, you can easily separate the two using redirection. For
example:
@@ -520,7 +499,7 @@ TEST(MyDeathTest, CompoundStatement) {
## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why?
Googletest needs to be able to create objects of your test fixture class, so it
GoogleTest needs to be able to create objects of your test fixture class, so it
must have a default constructor. Normally the compiler will define one for you.
However, there are cases where you have to define your own:
@@ -545,11 +524,11 @@ The new NPTL thread library doesn't suffer from this problem, as it doesn't
create a manager thread. However, if you don't control which machine your test
runs on, you shouldn't depend on this.
## Why does googletest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
## Why does GoogleTest require the entire test suite, instead of individual tests, to be named `*DeathTest` when it uses `ASSERT_DEATH`?
googletest does not interleave tests from different test suites. That is, it
GoogleTest does not interleave tests from different test suites. That is, it
runs all tests in one test suite first, and then runs all tests in the next test
suite, and so on. googletest does this because it needs to set up a test suite
suite, and so on. GoogleTest does this because it needs to set up a test suite
before the first test in it is run, and tear it down afterwards. Splitting up
the test case would require multiple set-up and tear-down processes, which is
inefficient and makes the semantics unclean.
@@ -570,7 +549,7 @@ interleave tests from different test suites, we need to run all tests in the
`FooTest` case before running any test in the `BarTest` case. This contradicts
with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
## But I don't like calling my entire test suite \*DeathTest when it contains both death tests and non-death tests. What do I do?
## But I don't like calling my entire test suite `*DeathTest` when it contains both death tests and non-death tests. What do I do?
You don't have to, but if you like, you may split up the test suite into
`FooTest` and `FooDeathTest`, where the names make it clear that they are
@@ -588,11 +567,11 @@ TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
```
## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
## GoogleTest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
Printing the LOG messages generated by the statement inside `EXPECT_DEATH()`
makes it harder to search for real problems in the parent's log. Therefore,
googletest only prints them when the death test has failed.
GoogleTest only prints them when the death test has failed.
If you really need to see such LOG messages, a workaround is to temporarily
break the death test (e.g. by changing the regex pattern it is expected to
@@ -607,11 +586,11 @@ defined such that we can print a value of `FooType`.
In addition, if `FooType` is declared in a name space, the `<<` operator also
needs to be defined in the *same* name space. See
[Tip of the Week #49](http://abseil.io/tips/49) for details.
[Tip of the Week #49](https://abseil.io/tips/49) for details.
## How do I suppress the memory leak messages on Windows?
Since the statically initialized googletest singleton requires allocations on
Since the statically initialized GoogleTest singleton requires allocations on
the heap, the Visual C++ memory leak detector will report memory leaks at the
end of the program run. The easiest way to avoid this is to use the
`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
@@ -625,13 +604,13 @@ things accordingly, you are leaking test-only logic into production code and
there is no easy way to ensure that the test-only code paths aren't run by
mistake in production. Such cleverness also leads to
[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly
advise against the practice, and googletest doesn't provide a way to do it.
advise against the practice, and GoogleTest doesn't provide a way to do it.
In general, the recommended way to cause the code to behave differently under
test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject
test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject
different functionality from the test and from the production code. Since your
production code doesn't link in the for-test logic at all (the
[`testonly`](http://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure
[`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure
that), there is no danger in accidentally running it.
However, if you *really*, *really*, *really* have no choice, and if you follow
@@ -654,7 +633,7 @@ the `--gtest_also_run_disabled_tests` flag.
Yes.
The rule is **all test methods in the same test suite must use the same fixture
class.** This means that the following is **allowed** because both tests use the
class**. This means that the following is **allowed** because both tests use the
same fixture class (`::testing::Test`).
```c++
@@ -672,7 +651,7 @@ TEST(CoolTest, DoSomething) {
```
However, the following code is **not allowed** and will produce a runtime error
from googletest because the test methods are using different test fixture
from GoogleTest because the test methods are using different test fixture
classes with the same test suite name.
```c++

View File

@@ -8,7 +8,7 @@ Given
```cpp
class Foo {
...
public:
virtual ~Foo();
virtual int GetSize() const = 0;
virtual string Describe(const char* name) = 0;
@@ -20,10 +20,10 @@ class Foo {
(note that `~Foo()` **must** be virtual) we can define its mock as
```cpp
#include "gmock/gmock.h"
#include <gmock/gmock.h>
class MockFoo : public Foo {
...
public:
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(string, Describe, (const char* name), (override));
MOCK_METHOD(string, Describe, (int type), (override));
@@ -58,7 +58,7 @@ To mock
```cpp
template <typename Elem>
class StackInterface {
...
public:
virtual ~StackInterface();
virtual int GetSize() const = 0;
virtual void Push(const Elem& x) = 0;
@@ -71,7 +71,7 @@ class StackInterface {
```cpp
template <typename Elem>
class MockStack : public StackInterface<Elem> {
...
public:
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(void, Push, (const Elem& x), (override));
};
@@ -140,7 +140,7 @@ To customize the default action for functions with return type `T`, use
// Sets the default action for return type std::unique_ptr<Buzz> to
// creating a new Buzz every time.
DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
[] { return MakeUnique<Buzz>(AccessLevel::kInternal); });
[] { return std::make_unique<Buzz>(AccessLevel::kInternal); });
// When this fires, the default action of MakeBuzz() will run, which
// will return a new Buzz object.

View File

@@ -177,7 +177,7 @@ class StackInterface {
template <typename Elem>
class MockStack : public StackInterface<Elem> {
...
MOCK_METHOD(int, GetSize, (), (override));
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(void, Push, (const Elem& x), (override));
};
```
@@ -285,6 +285,10 @@ If you are concerned about the performance overhead incurred by virtual
functions, and profiling confirms your concern, you can combine this with the
recipe for [mocking non-virtual methods](#MockingNonVirtualMethods).
Alternatively, instead of introducing a new interface, you can rewrite your code
to accept a std::function instead of the free function, and then use
[MockFunction](#MockFunction) to mock the std::function.
### Old-Style `MOCK_METHODn` Macros
Before the generic `MOCK_METHOD` macro
@@ -392,8 +396,7 @@ Old macros and their new equivalents:
If a mock method has no `EXPECT_CALL` spec but is called, we say that it's an
"uninteresting call", and the default action (which can be specified using
`ON_CALL()`) of the method will be taken. Currently, an uninteresting call will
also by default cause gMock to print a warning. (In the future, we might remove
this warning by default.)
also by default cause gMock to print a warning.
However, sometimes you may want to ignore these uninteresting calls, and
sometimes you may want to treat them as errors. gMock lets you make the decision
@@ -694,9 +697,9 @@ TEST(AbcTest, Xyz) {
EXPECT_CALL(foo, DoThat(_, _));
int n = 0;
EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked.
EXPECT_EQ(foo.DoThis(5), '+'); // FakeFoo::DoThis() is invoked.
foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked.
EXPECT_EQ(2, n);
EXPECT_EQ(n, 2);
}
```
@@ -905,7 +908,7 @@ using ::testing::Contains;
using ::testing::Property;
inline constexpr auto HasFoo = [](const auto& f) {
return Property(&MyClass::foo, Contains(f));
return Property("foo", &MyClass::foo, Contains(f));
};
...
EXPECT_THAT(x, HasFoo("blah"));
@@ -933,8 +936,8 @@ casts a matcher `m` to type `Matcher<T>`. To ensure safety, gMock checks that
floating-point numbers), the conversion from `T` to `U` is not lossy (in
other words, any value representable by `T` can also be represented by `U`);
and
3. When `U` is a reference, `T` must also be a reference (as the underlying
matcher may be interested in the address of the `U` value).
3. When `U` is a non-const reference, `T` must also be a reference (as the
underlying matcher may be interested in the address of the `U` value).
The code won't compile if any of these conditions isn't met.
@@ -1084,7 +1087,7 @@ using ::testing::Lt;
```
says that `Blah` will be called with arguments `x`, `y`, and `z` where `x < y <
z`. Note that in this example, it wasn't necessary specify the positional
z`. Note that in this example, it wasn't necessary to specify the positional
matchers.
As a convenience and example, gMock provides some matchers for 2-tuples,
@@ -1126,11 +1129,11 @@ using STL's `<functional>` header is just painful). For example, here's a
predicate that's satisfied by any number that is >= 0, <= 100, and != 50:
```cpp
using testing::AllOf;
using testing::Ge;
using testing::Le;
using testing::Matches;
using testing::Ne;
using ::testing::AllOf;
using ::testing::Ge;
using ::testing::Le;
using ::testing::Matches;
using ::testing::Ne;
...
Matches(AllOf(Ge(0), Le(100), Ne(50)))
```
@@ -1159,7 +1162,7 @@ int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
```
Note that the predicate function / functor doesn't have to return `bool`. It
works as long as the return value can be used as the condition in in statement
works as long as the return value can be used as the condition in the statement
`if (condition) ...`.
### Matching Arguments that Are Not Copyable
@@ -1300,23 +1303,27 @@ What if you have a pointer to pointer? You guessed it - you can use nested
`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points
to a number less than 3 (what a mouthful...).
### Testing a Certain Property of an Object
### Defining a Custom Matcher Class {#CustomMatcherClass}
Sometimes you want to specify that an object argument has a certain property,
but there is no existing matcher that does this. If you want good error
messages, you should [define a matcher](#NewMatchers). If you want to do it
quick and dirty, you could get away with writing an ordinary function.
Most matchers can be simply defined using [the MATCHER* macros](#NewMatchers),
which are terse and flexible, and produce good error messages. However, these
macros are not very explicit about the interfaces they create and are not always
suitable, especially for matchers that will be widely reused.
Let's say you have a mock function that takes an object of type `Foo`, which has
an `int bar()` method and an `int baz()` method, and you want to constrain that
the argument's `bar()` value plus its `baz()` value is a given number. Here's
how you can define a matcher to do it:
For more advanced cases, you may need to define your own matcher class. A custom
matcher allows you to test a specific invariant property of that object. Let's
take a look at how to do so.
Imagine you have a mock function that takes an object of type `Foo`, which has
an `int bar()` method and an `int baz()` method. You want to constrain that the
argument's `bar()` value plus its `baz()` value is a given number. (This is an
invariant.) Here's how we can write and use a matcher class to do so:
```cpp
using ::testing::Matcher;
class BarPlusBazEqMatcher {
public:
using is_gtest_matcher = void;
explicit BarPlusBazEqMatcher(int expected_sum)
: expected_sum_(expected_sum) {}
@@ -1325,23 +1332,24 @@ class BarPlusBazEqMatcher {
return (foo.bar() + foo.baz()) == expected_sum_;
}
void DescribeTo(std::ostream& os) const {
os << "bar() + baz() equals " << expected_sum_;
void DescribeTo(std::ostream* os) const {
*os << "bar() + baz() equals " << expected_sum_;
}
void DescribeNegationTo(std::ostream& os) const {
os << "bar() + baz() does not equal " << expected_sum_;
void DescribeNegationTo(std::ostream* os) const {
*os << "bar() + baz() does not equal " << expected_sum_;
}
private:
const int expected_sum_;
};
Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
::testing::Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
return BarPlusBazEqMatcher(expected_sum);
}
...
EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
Foo foo;
EXPECT_THAT(foo, BarPlusBazEq(5))...;
```
### Matching Containers
@@ -1420,11 +1428,12 @@ Use `Pair` when comparing maps or other associative containers.
{% raw %}
```cpp
using testing::ElementsAre;
using testing::Pair;
using ::testing::UnorderedElementsAre;
using ::testing::Pair;
...
std::map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};
EXPECT_THAT(m, ElementsAre(Pair("a", 1), Pair("b", 2), Pair("c", 3)));
absl::flat_hash_map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};
EXPECT_THAT(m, UnorderedElementsAre(
Pair("a", 1), Pair("b", 2), Pair("c", 3)));
```
{% endraw %}
@@ -1441,8 +1450,8 @@ using testing::Pair;
* If the container is passed by pointer instead of by reference, just write
`Pointee(ElementsAre*(...))`.
* The order of elements *matters* for `ElementsAre*()`. If you are using it
with containers whose element order are undefined (e.g. `hash_map`) you
should use `WhenSorted` around `ElementsAre`.
with containers whose element order are undefined (such as a
`std::unordered_map`) you should use `UnorderedElementsAre`.
### Sharing Matchers
@@ -1852,7 +1861,7 @@ error. So, what shall you do?
Though you may be tempted, DO NOT use `std::ref()`:
```cpp
using testing::Return;
using ::testing::Return;
class MockFoo : public Foo {
public:
@@ -1864,7 +1873,7 @@ class MockFoo : public Foo {
EXPECT_CALL(foo, GetValue())
.WillRepeatedly(Return(std::ref(x))); // Wrong!
x = 42;
EXPECT_EQ(42, foo.GetValue());
EXPECT_EQ(foo.GetValue(), 42);
```
Unfortunately, it doesn't work here. The above code will fail with error:
@@ -1886,20 +1895,20 @@ the expectation is set, and `Return(std::ref(x))` will always return 0.
returns the value pointed to by `pointer` at the time the action is *executed*:
```cpp
using testing::ReturnPointee;
using ::testing::ReturnPointee;
...
int x = 0;
MockFoo foo;
EXPECT_CALL(foo, GetValue())
.WillRepeatedly(ReturnPointee(&x)); // Note the & here.
x = 42;
EXPECT_EQ(42, foo.GetValue()); // This will succeed now.
EXPECT_EQ(foo.GetValue(), 42); // This will succeed now.
```
### Combining Actions
Want to do more than one thing when a function is called? That's fine. `DoAll()`
allow you to do sequence of actions every time. Only the return value of the
allows you to do a sequence of actions every time. Only the return value of the
last action in the sequence will be used.
```cpp
@@ -1918,6 +1927,12 @@ class MockFoo : public Foo {
action_n));
```
The return value of the last action **must** match the return type of the mocked
method. In the example above, `action_n` could be `Return(true)`, or a lambda
that returns a `bool`, but not `SaveArg`, which returns `void`. Otherwise the
signature of `DoAll` would not match the signature expected by `WillOnce`, which
is the signature of the mocked method, and it wouldn't compile.
### Verifying Complex Arguments {#SaveArgVerify}
If you want to verify that a method is called with a particular argument but the
@@ -2255,7 +2270,7 @@ TEST_F(FooTest, Test) {
EXPECT_CALL(foo, DoThis(2))
.WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5)));
EXPECT_EQ('+', foo.DoThis(2)); // Invokes SignOfSum(5, 2).
EXPECT_EQ(foo.DoThis(2), '+'); // Invokes SignOfSum(5, 2).
}
```
@@ -2631,8 +2646,8 @@ action will exhibit different behaviors. Example:
.WillRepeatedly(IncrementCounter(0));
foo.DoThis(); // Returns 1.
foo.DoThis(); // Returns 2.
foo.DoThat(); // Returns 1 - Blah() uses a different
// counter than Bar()'s.
foo.DoThat(); // Returns 1 - DoThat() uses a different
// counter than DoThis()'s.
```
versus
@@ -2762,36 +2777,33 @@ returns a null `unique_ptr`, thats what youll get if you dont specify a
action:
```cpp
using ::testing::IsNull;
...
// Use the default action.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"));
// Triggers the previous EXPECT_CALL.
EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello"));
EXPECT_THAT(mock_buzzer_.MakeBuzz("hello"), IsNull());
```
If you are not happy with the default action, you can tweak it as usual; see
[Setting Default Actions](#OnCall).
If you just need to return a pre-defined move-only value, you can use the
`Return(ByMove(...))` action:
If you just need to return a move-only value, you can use it in combination with
`WillOnce`. For example:
```cpp
// When this fires, the unique_ptr<> specified by ByMove(...) will
// be returned.
EXPECT_CALL(mock_buzzer_, MakeBuzz("world"))
.WillOnce(Return(ByMove(MakeUnique<Buzz>(AccessLevel::kInternal))));
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world"));
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"))
.WillOnce(Return(std::make_unique<Buzz>(AccessLevel::kInternal)));
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("hello"));
```
Note that `ByMove()` is essential here - if you drop it, the code wont compile.
Quiz time! What do you think will happen if a `Return(ByMove(...))` action is
performed more than once (e.g. you write `...
.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time
the action runs, the source value will be consumed (since its a move-only
value), so the next time around, theres no value to move from -- youll get a
run-time error that `Return(ByMove(...))` can only be run once.
Quiz time! What do you think will happen if a `Return` action is performed more
than once (e.g. you write `... .WillRepeatedly(Return(std::move(...)));`)? Come
think of it, after the first time the action runs, the source value will be
consumed (since its a move-only value), so the next time around, theres no
value to move from -- youll get a run-time error that `Return(std::move(...))`
can only be run once.
If you need your mock method to do more than just moving a pre-defined value,
remember that you can always use a lambda or a callable object, which can do
@@ -2800,7 +2812,7 @@ pretty much anything you want:
```cpp
EXPECT_CALL(mock_buzzer_, MakeBuzz("x"))
.WillRepeatedly([](StringPiece text) {
return MakeUnique<Buzz>(AccessLevel::kInternal);
return std::make_unique<Buzz>(AccessLevel::kInternal);
});
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
@@ -2808,7 +2820,7 @@ pretty much anything you want:
```
Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created
and returned. You cannot do this with `Return(ByMove(...))`.
and returned. You cannot do this with `Return(std::make_unique<...>(...))`.
That covers returning move-only values; but how do we work with methods
accepting move-only arguments? The answer is that they work normally, although
@@ -2819,7 +2831,7 @@ can always use `Return`, or a [lambda or functor](#FunctionsAsActions):
using ::testing::Unused;
EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true));
EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal)),
EXPECT_TRUE(mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal)),
0);
EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce(
@@ -2863,7 +2875,7 @@ method:
// When one calls ShareBuzz() on the MockBuzzer like this, the call is
// forwarded to DoShareBuzz(), which is mocked. Therefore this statement
// will trigger the above EXPECT_CALL.
mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), 0);
mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal), 0);
```
### Making the Compilation Faster
@@ -3188,11 +3200,11 @@ You can unlock this power by running your test with the `--gmock_verbose=info`
flag. For example, given the test program:
```cpp
#include "gmock/gmock.h"
#include <gmock/gmock.h>
using testing::_;
using testing::HasSubstr;
using testing::Return;
using ::testing::_;
using ::testing::HasSubstr;
using ::testing::Return;
class MockFoo {
public:
@@ -3300,7 +3312,7 @@ For convenience, we allow the description string to be empty (`""`), in which
case gMock will use the sequence of words in the matcher name as the
description.
For example:
#### Basic Example
```cpp
MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; }
@@ -3338,6 +3350,8 @@ If the above assertions fail, they will print something like:
where the descriptions `"is divisible by 7"` and `"not (is divisible by 7)"` are
automatically calculated from the matcher name `IsDivisibleBy7`.
#### Adding Custom Failure Messages
As you may have noticed, the auto-generated descriptions (especially those for
the negation) may not be so great. You can always override them with a `string`
expression of your own:
@@ -3371,21 +3385,48 @@ With this definition, the above assertion will give a better message:
Actual: 27 (the remainder is 6)
```
#### Using EXPECT_ Statements in Matchers
You can also use `EXPECT_...` statements inside custom matcher definitions. In
many cases, this allows you to write your matcher more concisely while still
providing an informative error message. For example:
```cpp
MATCHER(IsDivisibleBy7, "") {
const auto remainder = arg % 7;
EXPECT_EQ(remainder, 0);
return true;
}
```
If you write a test that includes the line `EXPECT_THAT(27, IsDivisibleBy7());`,
you will get an error something like the following:
```shell
Expected equality of these values:
remainder
Which is: 6
0
```
#### `MatchAndExplain`
You should let `MatchAndExplain()` print *any additional information* that can
help a user understand the match result. Note that it should explain why the
match succeeds in case of a success (unless it's obvious) - this is useful when
the matcher is used inside `Not()`. There is no need to print the argument value
itself, as gMock already prints it for you.
{: .callout .note}
NOTE: The type of the value being matched (`arg_type`) is determined by the
context in which you use the matcher and is supplied to you by the compiler, so
you don't need to worry about declaring it (nor can you). This allows the
matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match
any type where the value of `(arg % 7) == 0` can be implicitly converted to a
`bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an
`int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will
be `unsigned long`; and so on.
#### Argument Types
The type of the value being matched (`arg_type`) is determined by the context in
which you use the matcher and is supplied to you by the compiler, so you don't
need to worry about declaring it (nor can you). This allows the matcher to be
polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where
the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the
`Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`,
`arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be
`unsigned long`; and so on.
### Writing New Parameterized Matchers Quickly
@@ -3526,10 +3567,15 @@ just based on the number of parameters).
### Writing New Monomorphic Matchers
A matcher of argument type `T` implements the matcher interface for `T` and does
two things: it tests whether a value of type `T` matches the matcher, and can
describe what kind of values it matches. The latter ability is used for
generating readable error messages when expectations are violated.
A matcher of type `testing::Matcher<T>` implements the matcher interface for `T`
and does two things: it tests whether a value of type `T` matches the matcher,
and can describe what kind of values it matches. The latter ability is used for
generating readable error messages when expectations are violated. Some matchers
can even explain why it matches or doesn't match a certain value, which can be
helpful when the reason isn't obvious.
Because a matcher of type `testing::Matcher<T>` for a particular type `T` can
only be used to match a value of type `T`, we call it "monomorphic."
A matcher of `T` must declare a typedef like:
@@ -3621,8 +3667,16 @@ instead of `std::ostream*`.
### Writing New Polymorphic Matchers
Expanding what we learned above to *polymorphic* matchers is now just as simple
as adding templates in the right place.
Unlike a monomorphic matcher, which can only be used to match a value of a
particular type, a *polymorphic* matcher is one that can be used to match values
of multiple types. For example, `Eq(5)` is a polymorhpic matcher as it can be
used to match an `int`, a `double`, a `float`, and so on. You should think of a
polymorphic matcher as a *matcher factory* as opposed to a
`testing::Matcher<SomeType>` - itself is not an actual matcher, but can be
implicitly converted to a `testing::Matcher<SomeType>` depending on the context.
Expanding what we learned above to polymorphic matchers is now as simple as
adding templates in the right place.
```cpp
@@ -3748,6 +3802,26 @@ virtual.
Like in a monomorphic matcher, you may explain the match result by streaming
additional information to the `listener` argument in `MatchAndExplain()`.
### Implementing Composite Matchers {#CompositeMatchers}
Sometimes we want to define a matcher that takes other matchers as parameters.
For example, `DistanceFrom(target, m)` is a polymorphic matcher that takes a
matcher `m` as a parameter. It tests that the distance from `target` to the
value being matched satisfies sub-matcher `m`.
If you are implementing such a composite matcher, you'll need to generate the
description of the matcher based on the description(s) of its sub-matcher(s).
You can see the implementation of `DistanceFrom()` in
`googlemock/include/gmock/gmock-matchers.h` for an example. In particular, pay
attention to `DistanceFromMatcherImpl`. Notice that it stores the sub-matcher as
a `const Matcher<const Distance&> distance_matcher_` instead of a polymorphic
matcher - this allows it to call `distance_matcher_.DescribeTo(os)` to describe
the sub-matcher. If the sub-matcher is stored as a polymorphic matcher instead,
it would not be possible to get its description as in general polymorphic
matchers don't know how to describe themselves - they are matcher factories
instead of actual matchers; only after being converted to `Matcher<SomeType>`
can they be described.
### Writing New Cardinalities
A cardinality is used in `Times()` to tell gMock how many times you expect a
@@ -3807,35 +3881,74 @@ Cardinality EvenNumber() {
.Times(EvenNumber());
```
### Writing New Actions Quickly {#QuickNewActions}
### Writing New Actions {#QuickNewActions}
If the built-in actions don't work for you, you can easily define your own one.
Just define a functor class with a (possibly templated) call operator, matching
the signature of your action.
All you need is a call operator with a signature compatible with the mocked
function. So you can use a lambda:
```cpp
struct Increment {
template <typename T>
T operator()(T* arg) {
return ++(*arg);
}
}
MockFunction<int(int)> mock;
EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; });
EXPECT_EQ(mock.AsStdFunction()(2), 14);
```
The same approach works with stateful functors (or any callable, really):
Or a struct with a call operator (even a templated one):
```
```cpp
struct MultiplyBy {
template <typename T>
T operator()(T arg) { return arg * multiplier; }
int multiplier;
}
};
// Then use:
// EXPECT_CALL(...).WillOnce(MultiplyBy{7});
```
It's also fine for the callable to take no arguments, ignoring the arguments
supplied to the mock function:
```cpp
MockFunction<int(int)> mock;
EXPECT_CALL(mock, Call).WillOnce([] { return 17; });
EXPECT_EQ(mock.AsStdFunction()(0), 17);
```
When used with `WillOnce`, the callable can assume it will be called at most
once and is allowed to be a move-only type:
```cpp
// An action that contains move-only types and has an &&-qualified operator,
// demanding in the type system that it be called at most once. This can be
// used with WillOnce, but the compiler will reject it if handed to
// WillRepeatedly.
struct MoveOnlyAction {
std::unique_ptr<int> move_only_state;
std::unique_ptr<int> operator()() && { return std::move(move_only_state); }
};
MockFunction<std::unique_ptr<int>()> mock;
EXPECT_CALL(mock, Call).WillOnce(MoveOnlyAction{std::make_unique<int>(17)});
EXPECT_THAT(mock.AsStdFunction()(), Pointee(Eq(17)));
```
More generally, to use with a mock function whose signature is `R(Args...)` the
object can be anything convertible to `OnceAction<R(Args...)>` or
`Action<R(Args...)`>. The difference between the two is that `OnceAction` has
weaker requirements (`Action` requires a copy-constructible input that can be
called repeatedly whereas `OnceAction` requires only move-constructible and
supports `&&`-qualified call operators), but can be used only with `WillOnce`.
`OnceAction` is typically relevant only when supporting move-only types or
actions that want a type-system guarantee that they will be called at most once.
Typically the `OnceAction` and `Action` templates need not be referenced
directly in your actions: a struct or class with a call operator is sufficient,
as in the examples above. But fancier polymorphic actions that need to know the
specific return type of the mock function can define templated conversion
operators to make that possible. See `gmock-actions.h` for examples.
#### Legacy macro-based Actions
Before C++11, the functor-based actions were not supported; the old way of
@@ -4250,7 +4363,7 @@ particular type than to dump the bytes.
### Mock std::function {#MockFunction}
`std::function` is a general function type introduced in C++11. It is a
preferred way of passing callbacks to new interfaces. Functions are copiable,
preferred way of passing callbacks to new interfaces. Functions are copyable,
and are not usually passed around by pointer, which makes them tricky to mock.
But fear not - `MockFunction` can help you with that.

View File

@@ -369,8 +369,8 @@ Usually, if your action is for a particular function type, defining it using
different types (e.g. if you are defining `Return(*value*)`),
`MakePolymorphicAction()` is easiest. Sometimes you want precise control on what
types of functions the action can be used in, and implementing `ActionInterface`
is the way to go here. See the implementation of `Return()` in
`testing/base/public/gmock-actions.h` for an example.
is the way to go here. See the implementation of `Return()` in `gmock-actions.h`
for an example.
### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean?

View File

@@ -90,14 +90,14 @@ gMock is bundled with googletest.
## A Case for Mock Turtles
Let's look at an example. Suppose you are developing a graphics program that
relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like
relies on a [LOGO](https://en.wikipedia.org/wiki/Logo_programming_language)-like
API for drawing. How would you test that it does the right thing? Well, you can
run it and compare the screen with a golden screen snapshot, but let's admit it:
tests like this are expensive to run and fragile (What if you just upgraded to a
shiny new graphics card that has better anti-aliasing? Suddenly you have to
update all your golden images.). It would be too painful if all your tests are
like this. Fortunately, you learned about
[Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) and know the right thing
[Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) and know the right thing
to do: instead of having your application talk to the system API directly, wrap
the API in an interface (say, `Turtle`) and code to that interface:
@@ -164,7 +164,7 @@ follow:
After the process, you should have something like:
```cpp
#include "gmock/gmock.h" // Brings in gMock.
#include <gmock/gmock.h> // Brings in gMock.
class MockTurtle : public Turtle {
public:
@@ -190,10 +190,10 @@ Some people put it in a `_test.cc`. This is fine when the interface being mocked
`Foo` changes it, your test could break. (You can't really expect `Foo`'s
maintainer to fix every test that uses `Foo`, can you?)
So, the rule of thumb is: if you need to mock `Foo` and it's owned by others,
define the mock class in `Foo`'s package (better, in a `testing` sub-package
such that you can clearly separate production code and testing utilities), put
it in a `.h` and a `cc_library`. Then everyone can reference them from their
Generally, you should not mock classes you don't own. If you must mock such a
class owned by others, define the mock class in `Foo`'s Bazel package (usually
the same directory or a `testing` sub-directory), and put it in a `.h` and a
`cc_library` with `testonly=True`. Then everyone can reference them from their
tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and
only tests that depend on the changed methods need to be fixed.
@@ -224,8 +224,8 @@ Here's an example:
```cpp
#include "path/to/mock-turtle.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::AtLeast; // #1
@@ -261,6 +261,8 @@ happen. Therefore it's a good idea to turn on the heap checker in your tests
when you allocate mocks on the heap. You get that automatically if you use the
`gtest_main` library already.
###### Expectation Ordering
**Important note:** gMock requires expectations to be set **before** the mock
functions are called, otherwise the behavior is **undefined**. Do not alternate
between calls to `EXPECT_CALL()` and calls to the mock functions, and do not set

View File

@@ -19,19 +19,15 @@ examples here we assume you want to compile the sample
Using `pkg-config` in CMake is fairly easy:
```cmake
cmake_minimum_required(VERSION 3.0)
cmake_policy(SET CMP0048 NEW)
project(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX)
find_package(PkgConfig)
pkg_search_module(GTEST REQUIRED gtest_main)
add_executable(testapp samples/sample3_unittest.cc)
target_link_libraries(testapp ${GTEST_LDFLAGS})
target_compile_options(testapp PUBLIC ${GTEST_CFLAGS})
add_executable(testapp)
target_sources(testapp PRIVATE samples/sample3_unittest.cc)
target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS})
target_compile_options(testapp PRIVATE ${GTEST_CFLAGS})
include(CTest)
enable_testing()
add_test(first_and_only_test testapp)
```

View File

@@ -1,35 +1,8 @@
# Supported Platforms
GoogleTest requires a codebase and compiler compliant with the C++11 standard or
newer.
The GoogleTest code is officially supported on the following platforms.
Operating systems or tools not listed below are community-supported. For
community-supported platforms, patches that do not complicate the code may be
considered.
If you notice any problems on your platform, please file an issue on the
[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).
Pull requests containing fixes are welcome!
### Operating systems
* Linux
* macOS
* Windows
### Compilers
* gcc 5.0+
* clang 5.0+
* MSVC 2015+
**macOS users:** Xcode 9.3+ provides clang 5.0+.
### Build systems
* [Bazel](https://bazel.build/)
* [CMake](https://cmake.org/)
Bazel is the build system used by the team internally and in tests. CMake is
supported on a best-effort basis and by the community.
GoogleTest follows Google's
[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
See
[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
for a list of currently supported versions compilers, platforms, and build
tools.

View File

@@ -1,84 +1,84 @@
# Googletest Primer
# GoogleTest Primer
## Introduction: Why googletest?
## Introduction: Why GoogleTest?
*googletest* helps you write better C++ tests.
*GoogleTest* helps you write better C++ tests.
googletest is a testing framework developed by the Testing Technology team with
GoogleTest is a testing framework developed by the Testing Technology team with
Google's specific requirements and constraints in mind. Whether you work on
Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it
Linux, Windows, or a Mac, if you write C++ code, GoogleTest can help you. And it
supports *any* kind of tests, not just unit tests.
So what makes a good test, and how does googletest fit in? We believe:
So what makes a good test, and how does GoogleTest fit in? We believe:
1. Tests should be *independent* and *repeatable*. It's a pain to debug a test
that succeeds or fails as a result of other tests. googletest isolates the
that succeeds or fails as a result of other tests. GoogleTest isolates the
tests by running each of them on a different object. When a test fails,
googletest allows you to run it in isolation for quick debugging.
GoogleTest allows you to run it in isolation for quick debugging.
2. Tests should be well *organized* and reflect the structure of the tested
code. googletest groups related tests into test suites that can share data
code. GoogleTest groups related tests into test suites that can share data
and subroutines. This common pattern is easy to recognize and makes tests
easy to maintain. Such consistency is especially helpful when people switch
projects and start to work on a new code base.
3. Tests should be *portable* and *reusable*. Google has a lot of code that is
platform-neutral; its tests should also be platform-neutral. googletest
platform-neutral; its tests should also be platform-neutral. GoogleTest
works on different OSes, with different compilers, with or without
exceptions, so googletest tests can work with a variety of configurations.
exceptions, so GoogleTest tests can work with a variety of configurations.
4. When tests fail, they should provide as much *information* about the problem
as possible. googletest doesn't stop at the first test failure. Instead, it
as possible. GoogleTest doesn't stop at the first test failure. Instead, it
only stops the current test and continues with the next. You can also set up
tests that report non-fatal failures after which the current test continues.
Thus, you can detect and fix multiple bugs in a single run-edit-compile
cycle.
5. The testing framework should liberate test writers from housekeeping chores
and let them focus on the test *content*. googletest automatically keeps
and let them focus on the test *content*. GoogleTest automatically keeps
track of all tests defined, and doesn't require the user to enumerate them
in order to run them.
6. Tests should be *fast*. With googletest, you can reuse shared resources
6. Tests should be *fast*. With GoogleTest, you can reuse shared resources
across tests and pay for the set-up/tear-down only once, without making
tests depend on each other.
Since googletest is based on the popular xUnit architecture, you'll feel right
Since GoogleTest is based on the popular xUnit architecture, you'll feel right
at home if you've used JUnit or PyUnit before. If not, it will take you about 10
minutes to learn the basics and get started. So let's go!
## Beware of the nomenclature
## Beware of the Nomenclature
{: .callout .note}
_Note:_ There might be some confusion arising from different definitions of the
terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these.
*Note:* There might be some confusion arising from different definitions of the
terms *Test*, *Test Case* and *Test Suite*, so beware of misunderstanding these.
Historically, googletest started to use the term _Test Case_ for grouping
Historically, GoogleTest started to use the term *Test Case* for grouping
related tests, whereas current publications, including International Software
Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and
Testing Qualifications Board ([ISTQB](https://www.istqb.org/)) materials and
various textbooks on software quality, use the term
_[Test Suite][istqb test suite]_ for this.
*[Test Suite][istqb test suite]* for this.
The related term _Test_, as it is used in googletest, corresponds to the term
_[Test Case][istqb test case]_ of ISTQB and others.
The related term *Test*, as it is used in GoogleTest, corresponds to the term
*[Test Case][istqb test case]* of ISTQB and others.
The term _Test_ is commonly of broad enough sense, including ISTQB's definition
of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as
The term *Test* is commonly of broad enough sense, including ISTQB's definition
of *Test Case*, so it's not much of a problem here. But the term *Test Case* as
was used in Google Test is of contradictory sense and thus confusing.
googletest recently started replacing the term _Test Case_ with _Test Suite_.
GoogleTest recently started replacing the term *Test Case* with *Test Suite*.
The preferred API is *TestSuite*. The older TestCase API is being slowly
deprecated and refactored away.
So please be aware of the different definitions of the terms:
Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term
Meaning | GoogleTest Term | [ISTQB](https://www.istqb.org/) Term
:----------------------------------------------------------------------------------- | :---------------------- | :----------------------------------
Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
[istqb test case]: http://glossary.istqb.org/en/search/test%20case
[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite
[istqb test case]: https://glossary.istqb.org/en_US/term/test-case
[istqb test suite]: https://glossary.istqb.org/en_US/term/test-suite
## Basic Concepts
When using googletest, you start by writing *assertions*, which are statements
When using GoogleTest, you start by writing *assertions*, which are statements
that check whether a condition is true. An assertion's result can be *success*,
*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
current function; otherwise the program continues normally.
@@ -98,11 +98,11 @@ assertion level and building up to tests and test suites.
## Assertions
googletest assertions are macros that resemble function calls. You test a class
GoogleTest assertions are macros that resemble function calls. You test a class
or function by making assertions about its behavior. When an assertion fails,
googletest prints the assertion's source file and line number location, along
GoogleTest prints the assertion's source file and line number location, along
with a failure message. You may also supply a custom failure message which will
be appended to googletest's message.
be appended to GoogleTest's message.
The assertions come in pairs that test the same thing but have different effects
on the current function. `ASSERT_*` versions generate fatal failures when they
@@ -149,7 +149,7 @@ To create a test:
1. Use the `TEST()` macro to define and name a test function. These are
ordinary C++ functions that don't return a value.
2. In this function, along with any valid C++ statements you want to include,
use the various googletest assertions to check values.
use the various GoogleTest assertions to check values.
3. The test's result is determined by the assertions; if any assertion in the
test fails (either fatally or non-fatally), or if the test crashes, the
entire test fails. Otherwise, it succeeds.
@@ -190,7 +190,7 @@ TEST(FactorialTest, HandlesPositiveInput) {
}
```
googletest groups the test results by test suites, so logically related tests
GoogleTest groups the test results by test suites, so logically related tests
should be in the same test suite; in other words, the first argument to their
`TEST()` should be the same. In the above example, we have two tests,
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
@@ -210,7 +210,7 @@ objects for several different tests.
To create a fixture:
1. Derive a class from `::testing::Test` . Start its body with `protected:`, as
1. Derive a class from `testing::Test` . Start its body with `protected:`, as
we'll want to access fixture members from sub-classes.
2. Inside the class, declare any objects you plan to use.
3. If necessary, write a default constructor or `SetUp()` function to prepare
@@ -227,14 +227,14 @@ When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
access objects and subroutines in the test fixture:
```c++
TEST_F(TestFixtureName, TestName) {
TEST_F(TestFixtureClassName, TestName) {
... test body ...
}
```
Like `TEST()`, the first argument is the test suite name, but for `TEST_F()`
this must be the name of the test fixture class. You've probably guessed: `_F`
is for fixture.
Unlike `TEST()`, in `TEST_F()` the first argument must be the name of the test
fixture class. (`_F` stands for "Fixture"). No test suite name is specified for
this macro.
Unfortunately, the C++ macro system does not allow us to create a single macro
that can handle both types of tests. Using the wrong macro causes a compiler
@@ -244,12 +244,12 @@ Also, you must first define a test fixture class before using it in a
`TEST_F()`, or you'll get the compiler error "`virtual outside class
declaration`".
For each test defined with `TEST_F()`, googletest will create a *fresh* test
For each test defined with `TEST_F()`, GoogleTest will create a *fresh* test
fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean
up by calling `TearDown()`, and then delete the test fixture. Note that
different tests in the same test suite have different test fixture objects, and
googletest always deletes a test fixture before it creates the next one.
googletest does **not** reuse the same test fixture for multiple tests. Any
GoogleTest always deletes a test fixture before it creates the next one.
GoogleTest does **not** reuse the same test fixture for multiple tests. Any
changes one test makes to the fixture do not affect other tests.
As an example, let's write tests for a FIFO queue class named `Queue`, which has
@@ -271,15 +271,16 @@ First, define a fixture class. By convention, you should give it the name
`FooTest` where `Foo` is the class being tested.
```c++
class QueueTest : public ::testing::Test {
class QueueTest : public testing::Test {
protected:
void SetUp() override {
QueueTest() {
// q0_ remains empty
q1_.Enqueue(1);
q2_.Enqueue(2);
q2_.Enqueue(3);
}
// void TearDown() override {}
// ~QueueTest() override = default;
Queue<int> q0_;
Queue<int> q1_;
@@ -287,8 +288,9 @@ class QueueTest : public ::testing::Test {
};
```
In this case, `TearDown()` is not needed since we don't have to clean up after
each test, other than what's already done by the destructor.
In this case, we don't need to define a destructor or a `TearDown()` method,
because the implicit destructor generated by the compiler will perform all of
the necessary cleanup.
Now we'll write tests using `TEST_F()` and this fixture.
@@ -324,19 +326,17 @@ would lead to a segfault when `n` is `NULL`.
When these tests run, the following happens:
1. googletest constructs a `QueueTest` object (let's call it `t1`).
2. `t1.SetUp()` initializes `t1`.
3. The first test (`IsEmptyInitially`) runs on `t1`.
4. `t1.TearDown()` cleans up after the test finishes.
5. `t1` is destructed.
6. The above steps are repeated on another `QueueTest` object, this time
1. GoogleTest constructs a `QueueTest` object (let's call it `t1`).
2. The first test (`IsEmptyInitially`) runs on `t1`.
3. `t1` is destructed.
4. The above steps are repeated on another `QueueTest` object, this time
running the `DequeueWorks` test.
**Availability**: Linux, Windows, Mac.
## Invoking the Tests
`TEST()` and `TEST_F()` implicitly register their tests with googletest. So,
`TEST()` and `TEST_F()` implicitly register their tests with GoogleTest. So,
unlike with many other C++ testing frameworks, you don't have to re-list all
your defined tests in order to run them.
@@ -347,7 +347,7 @@ test suites, or even different source files.
When invoked, the `RUN_ALL_TESTS()` macro:
* Saves the state of all googletest flags.
* Saves the state of all GoogleTest flags.
* Creates a test fixture object for the first test.
@@ -359,7 +359,7 @@ When invoked, the `RUN_ALL_TESTS()` macro:
* Deletes the fixture.
* Restores the state of all googletest flags.
* Restores the state of all GoogleTest flags.
* Repeats the above steps for the next test, until all tests have run.
@@ -373,14 +373,14 @@ If a fatal failure happens the subsequent steps will be skipped.
> return the value of `RUN_ALL_TESTS()`.
>
> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than
> once conflicts with some advanced googletest features (e.g., thread-safe
> once conflicts with some advanced GoogleTest features (e.g., thread-safe
> [death tests](advanced.md#death-tests)) and thus is not supported.
**Availability**: Linux, Windows, Mac.
## Writing the main() Function
Most users should _not_ need to write their own `main` function and instead link
Most users should *not* need to write their own `main` function and instead link
with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry
point. See the end of this section for details. The remainder of this section
should only apply when you need to do something custom before the tests run that
@@ -394,14 +394,14 @@ You can start from this boilerplate:
```c++
#include "this/package/foo.h"
#include "gtest/gtest.h"
#include <gtest/gtest.h>
namespace my {
namespace project {
namespace {
// The fixture for testing class Foo.
class FooTest : public ::testing::Test {
class FooTest : public testing::Test {
protected:
// You can remove any or all of the following functions if their bodies would
// be empty.
@@ -449,14 +449,14 @@ TEST_F(FooTest, DoesXyz) {
} // namespace my
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
```
The `::testing::InitGoogleTest()` function parses the command line for
googletest flags, and removes all recognized flags. This allows the user to
control a test program's behavior via various flags, which we'll cover in the
The `testing::InitGoogleTest()` function parses the command line for GoogleTest
flags, and removes all recognized flags. This allows the user to control a test
program's behavior via various flags, which we'll cover in the
[AdvancedGuide](advanced.md). You **must** call this function before calling
`RUN_ALL_TESTS()`, or the flags won't be properly initialized.
@@ -475,7 +475,7 @@ NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
* Google Test is designed to be thread-safe. The implementation is thread-safe
on systems where the `pthreads` library is available. It is currently
_unsafe_ to use Google Test assertions from two threads concurrently on
*unsafe* to use Google Test assertions from two threads concurrently on
other systems (e.g. Windows). In most tests this is not an issue as usually
the assertions are done in the main thread. If you want to help, you can
volunteer to implement the necessary synchronization primitives in

View File

@@ -9,19 +9,18 @@ we recommend this tutorial as a starting point.
To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++11.
* [Bazel](https://bazel.build/), the preferred build system used by the
GoogleTest team.
* A compatible C++ compiler that supports at least C++14.
* [Bazel](https://bazel.build/) 7.0 or higher, the preferred build system used
by the GoogleTest team.
See [Supported Platforms](platforms.md) for more information about platforms
compatible with GoogleTest.
If you don't already have Bazel installed, see the
[Bazel installation guide](https://docs.bazel.build/versions/main/install.html).
[Bazel installation guide](https://bazel.build/install).
{: .callout .note}
Note: The terminal commands in this tutorial show a Unix shell prompt, but the
commands work on the Windows command line as well.
{: .callout .note} Note: The terminal commands in this tutorial show a Unix
shell prompt, but the commands work on the Windows command line as well.
## Set up a Bazel workspace
@@ -29,7 +28,7 @@ A
[Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace)
is a directory on your filesystem that you use to manage source files for the
software you want to build. Each workspace directory has a text file named
`WORKSPACE` which may be empty, or may contain references to external
`MODULE.bazel` which may be empty, or may contain references to external
dependencies required to build the outputs.
First, create a directory for your workspace:
@@ -38,30 +37,20 @@ First, create a directory for your workspace:
$ mkdir my_workspace && cd my_workspace
```
Next, youll create the `WORKSPACE` file to specify dependencies. A common and
recommended way to depend on GoogleTest is to use a
[Bazel external dependency](https://docs.bazel.build/versions/main/external.html)
via the
[`http_archive` rule](https://docs.bazel.build/versions/main/repo/http.html#http_archive).
To do this, in the root directory of your workspace (`my_workspace/`), create a
file named `WORKSPACE` with the following contents:
Next, youll create the `MODULE.bazel` file to specify dependencies. As of Bazel
7.0, the recommended way to consume GoogleTest is through the
[Bazel Central Registry](https://registry.bazel.build/modules/googletest). To do
this, create a `MODULE.bazel` file in the root directory of your Bazel workspace
with the following content:
```
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# MODULE.bazel
http_archive(
name = "com_google_googletest",
urls = ["https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip"],
strip_prefix = "googletest-609281088cfefc76f9d0ce82e1ff6c30cc3591e5",
)
# Choose the most recent version available at
# https://registry.bazel.build/modules/googletest
bazel_dep(name = "googletest", version = "1.15.2")
```
The above configuration declares a dependency on GoogleTest which is downloaded
as a ZIP archive from GitHub. In the above example,
`609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is the Git commit hash of the
GoogleTest version to use; we recommend updating the hash often to point to the
latest version.
Now you're ready to build C++ code that uses GoogleTest.
## Create and run a binary
@@ -93,23 +82,33 @@ following contents:
```
cc_test(
name = "hello_test",
size = "small",
srcs = ["hello_test.cc"],
deps = ["@com_google_googletest//:gtest_main"],
name = "hello_test",
size = "small",
srcs = ["hello_test.cc"],
deps = [
"@googletest//:gtest",
"@googletest//:gtest_main",
],
)
```
This `cc_test` rule declares the C++ test binary you want to build, and links to
GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE`
file (`@com_google_googletest`). For more information about Bazel `BUILD` files,
see the
the GoogleTest library (`@googletest//:gtest"`) and the GoogleTest `main()`
function (`@googletest//:gtest_main`). For more information about Bazel `BUILD`
files, see the
[Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html).
{: .callout .note}
NOTE: In the example below, we assume Clang or GCC and set `--cxxopt=-std=c++14`
to ensure that GoogleTest is compiled as C++14 instead of the compiler's default
setting (which could be C++11). For MSVC, the equivalent would be
`--cxxopt=/std:c++14`. See [Supported Platforms](platforms.md) for more details
on supported language versions.
Now you can build and run your test:
<pre>
<strong>my_workspace$ bazel test --test_output=all //:hello_test</strong>
<strong>$ bazel test --cxxopt=-std=c++14 --test_output=all //:hello_test</strong>
INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
INFO: Found 1 test target...
INFO: From Testing //:hello_test:

View File

@@ -10,7 +10,7 @@ this tutorial as a starting point. If your project uses Bazel, see the
To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++11.
* A compatible C++ compiler that supports at least C++14.
* [CMake](https://cmake.org/) and a compatible build tool for building the
project.
* Compatible build tools include
@@ -52,13 +52,14 @@ To do this, in your project directory (`my_project`), create a file named
cmake_minimum_required(VERSION 3.14)
project(my_project)
# GoogleTest requires at least C++11
set(CMAKE_CXX_STANDARD 11)
# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
@@ -66,7 +67,7 @@ FetchContent_MakeAvailable(googletest)
```
The above configuration declares a dependency on GoogleTest which is downloaded
from GitHub. In the above example, `609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is
from GitHub. In the above example, `03597a01ee50ed33e9dfd640b249b4be3799d395` is
the Git commit hash of the GoogleTest version to use; we recommend updating the
hash often to point to the latest version.
@@ -108,7 +109,7 @@ add_executable(
)
target_link_libraries(
hello_test
gtest_main
GTest::gtest_main
)
include(GoogleTest)

View File

@@ -24,7 +24,8 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace.
| :--------------------------------- | :-------------------------------------- |
| `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`. |
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer` by copy-assignment. |
| `SaveArgByMove<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer` by move-assignment. |
| `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. |

View File

@@ -1,7 +1,7 @@
# Assertions Reference
This page lists the assertion macros provided by GoogleTest for verifying code
behavior. To use them, include the header `gtest/gtest.h`.
behavior. To use them, add `#include <gtest/gtest.h>`.
The majority of the macros listed below come as a pair with an `EXPECT_` variant
and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal
@@ -88,7 +88,7 @@ For example, the following code verifies that the string `value1` starts with
10:
```cpp
#include "gmock/gmock.h"
#include <gmock/gmock.h>
using ::testing::AllOf;
using ::testing::Gt;
@@ -276,7 +276,8 @@ Units in the Last Place (ULPs). To learn more about ULPs, see the article
`ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)`
Verifies that the two `float` values *`val1`* and *`val2`* are approximately
equal, to within 4 ULPs from each other.
equal, to within 4 ULPs from each other. Infinity and the largest finite float
value are considered to be one ULP apart.
### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ}
@@ -284,7 +285,8 @@ equal, to within 4 ULPs from each other.
`ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)`
Verifies that the two `double` values *`val1`* and *`val2`* are approximately
equal, to within 4 ULPs from each other.
equal, to within 4 ULPs from each other. Infinity and the largest finite double
value are considered to be one ULP apart.
### EXPECT_NEAR {#EXPECT_NEAR}
@@ -294,6 +296,11 @@ equal, to within 4 ULPs from each other.
Verifies that the difference between *`val1`* and *`val2`* does not exceed the
absolute error bound *`abs_error`*.
If *`val`* and *`val2`* are both infinity of the same sign, the difference is
considered to be 0. Otherwise, if either value is infinity, the difference is
considered to be infinity. All non-NaN values (including infinity) are
considered to not exceed an *`abs_error`* of infinity.
## Exception Assertions {#exceptions}
The following assertions verify that a piece of code throws, or does not throw,
@@ -515,7 +522,7 @@ Verifies that *`expression`* is a success `HRESULT`.
### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED}
`EXPECT_HRESULT_FAILED(`*`expression`*`)` \
`EXPECT_HRESULT_FAILED(`*`expression`*`)`
`ASSERT_HRESULT_FAILED(`*`expression`*`)`
Verifies that *`expression`* is a failure `HRESULT`.

View File

@@ -8,9 +8,13 @@ A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or
| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. |
| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. |
{: .callout .note}
**Note:** Although equality matching via `EXPECT_THAT(actual_value,
expected_value)` is supported, prefer to make the comparison explicit via
{: .callout .warning}
**WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)`
is supported, however note that implicit conversions can cause surprising
results. For example, `EXPECT_THAT(some_bool, "some string")` will compile and
may pass unintentionally.
**BEST PRACTICE:** Prefer to make the comparison explicit via
`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value,
expected_value)`.
@@ -38,6 +42,8 @@ Matcher | Description
| `Lt(value)` | `argument < value` |
| `Ne(value)` | `argument != value` |
| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. |
| `DistanceFrom(target, m)` | The distance between `argument` and `target` (computed by `abs(argument - target)`) matches `m`. |
| `DistanceFrom(target, get_distance, m)` | The distance between `argument` and `target` (computed by `get_distance(argument, target)`) matches `m`. |
| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. |
| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). |
| `NotNull()` | `argument` is a non-null pointer (raw or smart). |
@@ -98,7 +104,7 @@ The `argument` can be either a C string or a C++ string object:
| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. |
| `StrEq(string)` | `argument` is equal to `string`. |
| `StrNe(string)` | `argument` is not equal to `string`. |
| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. |
| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. The web-safe format from [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648#section-5) is supported. |
`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
use the regular expression syntax defined
@@ -167,6 +173,11 @@ messages, you can use:
| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. |
| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message.
{: .callout .warning}
Warning: Don't use `Property()` against member functions that you do not own,
because taking addresses of functions is fragile and generally not part of the
contract of the function.
**Notes:**
* You can use `FieldsAre()` to match any type that supports structured
@@ -185,15 +196,12 @@ messages, you can use:
EXPECT_THAT(s, FieldsAre(42, "aloha"));
```
* Don't use `Property()` against member functions that you do not own, because
taking addresses of functions is fragile and generally not part of the
contract of the function.
## Matching the Result of a Function, Functor, or Callback
| Matcher | Description |
| :--------------- | :------------------------------------------------ |
| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. |
| `ResultOf(result_description, f, m)` | The same as the two-parameter version, but provides a better error message.
## Pointer Matchers
@@ -283,3 +291,15 @@ which must be a permanent callback.
return ExplainMatchResult(matcher, arg.nested().property(), result_listener);
}
```
5. You can use `DescribeMatcher<>` to describe another matcher. For example:
```cpp
MATCHER_P(XAndYThat, matcher,
"X that " + DescribeMatcher<int>(matcher, negation) +
(negation ? " or" : " and") + " Y that " +
DescribeMatcher<double>(matcher, negation)) {
return ExplainMatchResult(matcher, arg.x(), result_listener) &&
ExplainMatchResult(matcher, arg.y(), result_listener);
}
```

View File

@@ -1,8 +1,7 @@
# Mocking Reference
This page lists the facilities provided by GoogleTest for creating and working
with mock objects. To use them, include the header
`gmock/gmock.h`.
with mock objects. To use them, add `#include <gmock/gmock.h>`.
## Macros {#macros}
@@ -248,7 +247,9 @@ EXPECT_CALL(my_mock, GetNumber())
.WillOnce(Return(3));
```
The `WillOnce` clause can be used any number of times on an expectation.
The `WillOnce` clause can be used any number of times on an expectation. Unlike
`WillRepeatedly`, the action fed to each `WillOnce` call will be called at most
once, so may be a move-only type and/or have an `&&`-qualified call operator.
#### WillRepeatedly {#EXPECT_CALL.WillRepeatedly}

View File

@@ -3,7 +3,7 @@
<!--* toc_depth: 3 *-->
This page lists the facilities provided by GoogleTest for writing test programs.
To use them, include the header `gtest/gtest.h`.
To use them, add `#include <gtest/gtest.h>`.
## Macros
@@ -94,7 +94,8 @@ Instantiates the value-parameterized test suite *`TestSuiteName`* (defined with
The argument *`InstantiationName`* is a unique name for the instantiation of the
test suite, to distinguish between multiple instantiations. In test output, the
instantiation name is added as a prefix to the test suite name
*`TestSuiteName`*.
*`TestSuiteName`*. If *`InstantiationName`* is empty
(`INSTANTIATE_TEST_SUITE_P(, ...)`), no prefix is added.
The argument *`param_generator`* is one of the following GoogleTest-provided
functions that generate the test parameters, all defined in the `::testing`
@@ -109,6 +110,7 @@ namespace:
| `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. |
| `Bool()` | Yields sequence `{false, true}`. |
| `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. |
| `ConvertGenerator<T>(g)` or `ConvertGenerator(g, func)` | Yields values generated by generator `g`, `static_cast` from `T`. (Note: `T` might not be what you expect. See [*Using ConvertGenerator*](#using-convertgenerator) below.) The second overload uses `func` to perform the conversion. |
The optional last argument *`name_generator`* is a function or functor that
generates custom test name suffixes based on the test parameters. The function
@@ -121,8 +123,8 @@ custom function can be used for more control:
```cpp
INSTANTIATE_TEST_SUITE_P(
MyInstantiation, MyTestSuite,
::testing::Values(...),
[](const ::testing::TestParamInfo<MyTestSuite::ParamType>& info) {
testing::Values(...),
[](const testing::TestParamInfo<MyTestSuite::ParamType>& info) {
// Can use info.param here to generate the test suffix
std::string name = ...
return name;
@@ -135,9 +137,107 @@ For more information, see
See also
[`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST`](#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST).
###### Using `ConvertGenerator`
The functions listed in the table above appear to return generators that create
values of the desired types, but this is not generally the case. Rather, they
typically return factory objects that convert to the the desired generators.
This affords some flexibility in allowing you to specify values of types that
are different from, yet implicitly convertible to, the actual parameter type
required by your fixture class.
For example, you can do the following with a fixture that requires an `int`
parameter:
```cpp
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
testing::Values(1, 1.2)); // Yes, Values() supports heterogeneous argument types.
```
It might seem obvious that `1.2` &mdash; a `double` &mdash; will be converted to
an `int` but in actuality it requires some template gymnastics involving the
indirection described in the previous paragraph.
What if your parameter type is not implicitly convertible from the generated
type but is *explicitly* convertible? There will be no automatic conversion, but
you can force it by applying `ConvertGenerator<T>`. The compiler can
automatically deduce the target type (your fixture's parameter type), but
because of the aforementioned indirection it cannot decide what the generated
type should be. You need to tell it, by providing the type `T` explicitly. Thus
`T` should not be your fixture's parameter type, but rather an intermediate type
that is supported by the factory object, and which can be `static_cast` to the
fixture's parameter type:
```cpp
// The fixture's parameter type.
class MyParam {
public:
// Explicit converting ctor.
explicit MyParam(const std::tuple<int, bool>& t);
...
};
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
ConvertGenerator<std::tuple<int, bool>>(Combine(Values(0.1, 1.2), Bool())));
```
In this example `Combine` supports the generation of `std::tuple<int, bool>>`
objects (even though the provided values for the first tuple element are
`double`s) and those `tuple`s get converted into `MyParam` objects by virtue of
the call to `ConvertGenerator`.
For parameter types that are not convertible from the generated types you can
provide a callable that does the conversion. The callable accepts an object of
the generated type and returns an object of the fixture's parameter type. The
generated type can often be deduced by the compiler from the callable's call
signature so you do not usually need specify it explicitly (but see a caveat
below).
```cpp
// The fixture's parameter type.
class MyParam {
public:
MyParam(int, bool);
...
};
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
ConvertGenerator(Combine(Values(1, 1.2), Bool()),
[](const std::tuple<int i, bool>& t){
const auto [i, b] = t;
return MyParam(i, b);
}));
```
The callable may be anything that can be used to initialize a `std::function`
with the appropriate call signature. Note the callable's return object gets
`static_cast` to the fixture's parameter type, so it does not have to be of that
exact type, only convertible to it.
**Caveat:** Consider the following example.
```cpp
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
ConvertGenerator(Values(std::string("s")), [](std::string_view s) { ... }));
```
The `string` argument gets copied into the factory object returned by `Values`.
Then, because the generated type deduced from the lambda is `string_view`, the
factory object spawns a generator that holds a `string_view` referencing that
`string`. Unfortunately, by the time this generator gets invoked, the factory
object is gone and the `string_view` is dangling.
To overcome this problem you can specify the generated type explicitly:
`ConvertGenerator<std::string>(Values(std::string("s")), [](std::string_view s)
{ ... })`. Alternatively, you can change the lambda's signature to take a
`std::string` or a `const std::string&` (the latter will not leave you with a
dangling reference because the type deduction strips off the reference and the
`const`).
### TYPED_TEST_SUITE {#TYPED_TEST_SUITE}
`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)`
`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`,`*`NameGenerator`*`)`
Defines a typed test suite based on the test fixture *`TestFixtureName`*. The
test suite name is *`TestFixtureName`*.
@@ -147,7 +247,7 @@ type, for example:
```cpp
template <typename T>
class MyFixture : public ::testing::Test {
class MyFixture : public testing::Test {
public:
...
using List = std::list<T>;
@@ -167,6 +267,22 @@ TYPED_TEST_SUITE(MyFixture, MyTypes);
The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE`
macro to parse correctly.
The optional third argument *`NameGenerator`* allows specifying a class that
exposes a templated static function `GetName(int)`. For example:
```cpp
class NameGenerator {
public:
template <typename T>
static std::string GetName(int) {
if constexpr (std::is_same_v<T, char>) return "char";
if constexpr (std::is_same_v<T, int>) return "int";
if constexpr (std::is_same_v<T, unsigned int>) return "unsignedInt";
}
};
TYPED_TEST_SUITE(MyFixture, MyTypes, NameGenerator);
```
See also [`TYPED_TEST`](#TYPED_TEST) and
[Typed Tests](../advanced.md#typed-tests) for more information.
@@ -276,7 +392,8 @@ must be registered with
The argument *`InstantiationName`* is a unique name for the instantiation of the
test suite, to distinguish between multiple instantiations. In test output, the
instantiation name is added as a prefix to the test suite name
*`TestSuiteName`*.
*`TestSuiteName`*. If *`InstantiationName`* is empty
(`INSTANTIATE_TYPED_TEST_SUITE_P(, ...)`), no prefix is added.
The argument *`Types`* is a [`Types`](#Types) object representing the list of
types to run the tests on, for example:
@@ -323,7 +440,7 @@ Then the test code should look like:
```cpp
namespace my_namespace {
class MyClassTest : public ::testing::Test {
class MyClassTest : public testing::Test {
...
};
@@ -386,7 +503,7 @@ GoogleTest defines the following classes and types to help with writing tests.
### AssertionResult {#AssertionResult}
`::testing::AssertionResult`
`testing::AssertionResult`
A class for indicating whether an assertion was successful.
@@ -400,14 +517,14 @@ To create an instance of this class, use one of the factory functions
### AssertionException {#AssertionException}
`::testing::AssertionException`
`testing::AssertionException`
Exception which can be thrown from
[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult).
### EmptyTestEventListener {#EmptyTestEventListener}
`::testing::EmptyTestEventListener`
`testing::EmptyTestEventListener`
Provides an empty implementation of all methods in the
[`TestEventListener`](#TestEventListener) interface, such that a subclass only
@@ -415,7 +532,7 @@ needs to override the methods it cares about.
### Environment {#Environment}
`::testing::Environment`
`testing::Environment`
Represents a global test environment. See
[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down).
@@ -436,7 +553,7 @@ Override this to define how to tear down the environment.
### ScopedTrace {#ScopedTrace}
`::testing::ScopedTrace`
`testing::ScopedTrace`
An instance of this class causes a trace to be included in every test failure
message generated by code in the scope of the lifetime of the `ScopedTrace`
@@ -452,7 +569,7 @@ ScopedTrace(const char* file, int line, const T& message)
Example usage:
```cpp
::testing::ScopedTrace trace("file.cc", 123, "message");
testing::ScopedTrace trace("file.cc", 123, "message");
```
The resulting trace includes the given source file path and line number, and the
@@ -463,7 +580,7 @@ See also [`SCOPED_TRACE`](#SCOPED_TRACE).
### Test {#Test}
`::testing::Test`
`testing::Test`
The abstract class that all tests inherit from. `Test` is not copyable.
@@ -518,8 +635,8 @@ Logs a property for the current test, test suite, or entire invocation of the
test program. Only the last value for a given key is logged.
The key must be a valid XML attribute name, and cannot conflict with the ones
already used by GoogleTest (`name`, `status`, `time`, `classname`, `type_param`,
and `value_param`).
already used by GoogleTest (`name`, `file`, `line`, `status`, `time`,
`classname`, `type_param`, and `value_param`).
`RecordProperty` is `public static` so it can be called from utility functions
that are not members of the test fixture.
@@ -551,7 +668,7 @@ after running each individual test.
### TestWithParam {#TestWithParam}
`::testing::TestWithParam<T>`
`testing::TestWithParam<T>`
A convenience class which inherits from both [`Test`](#Test) and
[`WithParamInterface<T>`](#WithParamInterface).
@@ -671,7 +788,7 @@ during execution of `SetUpTestSuite` and `TearDownTestSuite`.
### TestInfo {#TestInfo}
`::testing::TestInfo`
`testing::TestInfo`
Stores information about a test.
@@ -750,7 +867,7 @@ Returns the result of the test. See [`TestResult`](#TestResult).
### TestParamInfo {#TestParamInfo}
`::testing::TestParamInfo<T>`
`testing::TestParamInfo<T>`
Describes a parameter to a value-parameterized test. The type `T` is the type of
the parameter.
@@ -760,7 +877,7 @@ and its integer index respectively.
### UnitTest {#UnitTest}
`::testing::UnitTest`
`testing::UnitTest`
This class contains information about the test program.
@@ -928,7 +1045,7 @@ GoogleTest. See [`TestEventListeners`](#TestEventListeners).
### TestEventListener {#TestEventListener}
`::testing::TestEventListener`
`testing::TestEventListener`
The interface for tracing execution of tests. The methods below are listed in
the order the corresponding events are fired.
@@ -1026,7 +1143,7 @@ Fired after all test activities have ended.
### TestEventListeners {#TestEventListeners}
`::testing::TestEventListeners`
`testing::TestEventListeners`
Lets users add listeners to track events in GoogleTest.
@@ -1071,7 +1188,7 @@ the caller and makes this function return `NULL` the next time.
### TestPartResult {#TestPartResult}
`::testing::TestPartResult`
`testing::TestPartResult`
A copyable object representing the result of a test part (i.e. an assertion or
an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`).
@@ -1153,7 +1270,7 @@ Returns true if and only if the test part failed.
### TestProperty {#TestProperty}
`::testing::TestProperty`
`testing::TestProperty`
A copyable object representing a user-specified test property which can be
output as a key/value string pair.
@@ -1180,7 +1297,7 @@ Sets a new value, overriding the previous one.
### TestResult {#TestResult}
`::testing::TestResult`
`testing::TestResult`
Contains information about the result of a single test.
@@ -1261,20 +1378,20 @@ range, aborts the program.
### TimeInMillis {#TimeInMillis}
`::testing::TimeInMillis`
`testing::TimeInMillis`
An integer type representing time in milliseconds.
### Types {#Types}
`::testing::Types<T...>`
`testing::Types<T...>`
Represents a list of types for use in typed tests and type-parameterized tests.
The template argument `T...` can be any number of types, for example:
```
::testing::Types<char, int, unsigned int>
testing::Types<char, int, unsigned int>
```
See [Typed Tests](../advanced.md#typed-tests) and
@@ -1283,7 +1400,7 @@ information.
### WithParamInterface {#WithParamInterface}
`::testing::WithParamInterface<T>`
`testing::WithParamInterface<T>`
The pure interface class that all value-parameterized tests inherit from.
@@ -1309,14 +1426,16 @@ tests.
### InitGoogleTest {#InitGoogleTest}
`void ::testing::InitGoogleTest(int* argc, char** argv)` \
`void ::testing::InitGoogleTest(int* argc, wchar_t** argv)` \
`void ::testing::InitGoogleTest()`
`void testing::InitGoogleTest(int* argc, char** argv)` \
`void testing::InitGoogleTest(int* argc, wchar_t** argv)` \
`void testing::InitGoogleTest()`
Initializes GoogleTest. This must be called before calling
[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line
for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it
is removed from `argv`, and `*argc` is decremented.
is removed from `argv`, and `*argc` is decremented. Keep in mind that `argv`
must terminate with a `NULL` pointer (i.e. `argv[argc]` is `NULL`), which is
already the case with the default `argv` passed to `main`.
No value is returned. Instead, the GoogleTest flag variables are updated.
@@ -1328,7 +1447,7 @@ platforms where there is no `argc`/`argv`.
### AddGlobalTestEnvironment {#AddGlobalTestEnvironment}
`Environment* ::testing::AddGlobalTestEnvironment(Environment* env)`
`Environment* testing::AddGlobalTestEnvironment(Environment* env)`
Adds a test environment to the test program. Must be called before
[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See
@@ -1341,7 +1460,7 @@ See also [`Environment`](#Environment).
```cpp
template <typename Factory>
TestInfo* ::testing::RegisterTest(const char* test_suite_name, const char* test_name,
TestInfo* testing::RegisterTest(const char* test_suite_name, const char* test_name,
const char* type_param, const char* value_param,
const char* file, int line, Factory factory)
```
@@ -1380,27 +1499,27 @@ an all-caps name.
### AssertionSuccess {#AssertionSuccess}
`AssertionResult ::testing::AssertionSuccess()`
`AssertionResult testing::AssertionSuccess()`
Creates a successful assertion result. See
[`AssertionResult`](#AssertionResult).
### AssertionFailure {#AssertionFailure}
`AssertionResult ::testing::AssertionFailure()`
`AssertionResult testing::AssertionFailure()`
Creates a failed assertion result. Use the `<<` operator to store a failure
message:
```cpp
::testing::AssertionFailure() << "My failure message";
testing::AssertionFailure() << "My failure message";
```
See [`AssertionResult`](#AssertionResult).
### StaticAssertTypeEq {#StaticAssertTypeEq}
`::testing::StaticAssertTypeEq<T1, T2>()`
`testing::StaticAssertTypeEq<T1, T2>()`
Compile-time assertion for type equality. Compiles if and only if `T1` and `T2`
are the same type. The value it returns is irrelevant.
@@ -1409,7 +1528,7 @@ See [Type Assertions](../advanced.md#type-assertions) for more information.
### PrintToString {#PrintToString}
`std::string ::testing::PrintToString(x)`
`std::string testing::PrintToString(x)`
Prints any value `x` using GoogleTest's value printer.
@@ -1419,7 +1538,7 @@ for more information.
### PrintToStringParamName {#PrintToStringParamName}
`std::string ::testing::PrintToStringParamName(TestParamInfo<T>& info)`
`std::string testing::PrintToStringParamName(TestParamInfo<T>& info)`
A built-in parameterized test name generator which returns the result of
[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the

View File

@@ -1,7 +1,7 @@
# Googletest Samples
If you're like us, you'd like to look at
[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples)
[googletest samples.](https://github.com/google/googletest/blob/main/googletest/samples)
The sample directory has a number of well-commented samples showing how to use a
variety of googletest features.