Debian Codegraph @

src/external/googletest/docs/advanced.md

raw
1 # Advanced GoogleTest Topics
2
3 ## Introduction
4
5 Now that you have read the [GoogleTest Primer](primer.md) and learned how to
6 write tests using GoogleTest, it's time to learn some new tricks. This document
7 will show you more assertions as well as how to construct complex failure
8 messages, propagate fatal failures, reuse and speed up your test fixtures, and
9 use various flags with your tests.
10
11 ## More Assertions
12
13 This section covers some less frequently used, but still significant,
14 assertions.
15
16 ### Explicit Success and Failure
17
18 See [Explicit Success and Failure](reference/assertions.md#success-failure) in
19 the Assertions Reference.
20
21 ### Exception Assertions
22
23 See [Exception Assertions](reference/assertions.md#exceptions) in the Assertions
24 Reference.
25
26 ### Predicate Assertions for Better Error Messages
27
28 Even though GoogleTest has a rich set of assertions, they can never be complete,
29 as it's impossible (nor a good idea) to anticipate all scenarios a user might
30 run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a
31 complex expression, for lack of a better macro. This has the problem of not
32 showing you the values of the parts of the expression, making it hard to
33 understand what went wrong. As a workaround, some users choose to construct the
34 failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
35 is awkward especially when the expression has side-effects or is expensive to
36 evaluate.
37
38 GoogleTest gives you three different options to solve this problem:
39
40 #### Using an Existing Boolean Function
41
42 If you already have a function or functor that returns `bool` (or a type that
43 can be implicitly converted to `bool`), you can use it in a *predicate
44 assertion* to get the function arguments printed for free. See
45 [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions
46 Reference for details.
47
48 #### Using a Function That Returns an AssertionResult
49
50 While `EXPECT_PRED*()` and friends are handy for a quick job, the syntax is not
51 satisfactory: you have to use different macros for different arities, and it
52 feels more like Lisp than C++. The `::testing::AssertionResult` class solves
53 this problem.
54
55 An `AssertionResult` object represents the result of an assertion (whether it's
56 a success or a failure, and an associated message). You can create an
57 `AssertionResult` using one of these factory functions:
58
59 ```c++
60 namespace testing {
61
62 // Returns an AssertionResult object to indicate that an assertion has
63 // succeeded.
64 AssertionResult AssertionSuccess();
65
66 // Returns an AssertionResult object to indicate that an assertion has
67 // failed.
68 AssertionResult AssertionFailure();
69
70 }
71 ```
72
73 You can then use the `<<` operator to stream messages to the `AssertionResult`
74 object.
75
76 To provide more readable messages in Boolean assertions (e.g. `EXPECT_TRUE()`),
77 write a predicate function that returns `AssertionResult` instead of `bool`. For
78 example, if you define `IsEven()` as:
79
80 ```c++
81 testing::AssertionResult IsEven(int n) {
82 if ((n % 2) == 0)
83 return testing::AssertionSuccess();
84 else
85 return testing::AssertionFailure() << n << " is odd";
86 }
87 ```
88
89 instead of:
90
91 ```c++
92 bool IsEven(int n) {
93 return (n % 2) == 0;
94 }
95 ```
96
97 the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print:
98
99 ```none
100 Value of: IsEven(Fib(4))
101 Actual: false (3 is odd)
102 Expected: true
103 ```
104
105 instead of a more opaque
106
107 ```none
108 Value of: IsEven(Fib(4))
109 Actual: false
110 Expected: true
111 ```
112
113 If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` as well
114 (one third of Boolean assertions in the Google code base are negative ones), and
115 are fine with making the predicate slower in the success case, you can supply a
116 success message:
117
118 ```c++
119 testing::AssertionResult IsEven(int n) {
120 if ((n % 2) == 0)
121 return testing::AssertionSuccess() << n << " is even";
122 else
123 return testing::AssertionFailure() << n << " is odd";
124 }
125 ```
126
127 Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print
128
129 ```none
130 Value of: IsEven(Fib(6))
131 Actual: true (8 is even)
132 Expected: false
133 ```
134
135 #### Using a Predicate-Formatter
136
137 If you find the default message generated by
138 [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) and
139 [`EXPECT_TRUE`](reference/assertions.md#EXPECT_TRUE) unsatisfactory, or some
140 arguments to your predicate do not support streaming to `ostream`, you can
141 instead use *predicate-formatter assertions* to *fully* customize how the
142 message is formatted. See
143 [`EXPECT_PRED_FORMAT*`](reference/assertions.md#EXPECT_PRED_FORMAT) in the
144 Assertions Reference for details.
145
146 ### Floating-Point Comparison
147
148 See [Floating-Point Comparison](reference/assertions.md#floating-point) in the
149 Assertions Reference.
150
151 #### Floating-Point Predicate-Format Functions
152
153 Some floating-point operations are useful, but not that often used. In order to
154 avoid an explosion of new macros, we provide them as predicate-format functions
155 that can be used in the predicate assertion macro
156 [`EXPECT_PRED_FORMAT2`](reference/assertions.md#EXPECT_PRED_FORMAT), for
157 example:
158
159 ```c++
160 using ::testing::FloatLE;
161 using ::testing::DoubleLE;
162 ...
163 EXPECT_PRED_FORMAT2(FloatLE, val1, val2);
164 EXPECT_PRED_FORMAT2(DoubleLE, val1, val2);
165 ```
166
167 The above code verifies that `val1` is less than, or approximately equal to,
168 `val2`.
169
170 ### Asserting Using gMock Matchers
171
172 See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions
173 Reference.
174
175 ### More String Assertions
176
177 (Please read the [previous](#asserting-using-gmock-matchers) section first if
178 you haven't.)
179
180 You can use the gMock [string matchers](reference/matchers.md#string-matchers)
181 with [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) to do more string
182 comparison tricks (sub-string, prefix, suffix, regular expression, and etc). For
183 example,
184
185 ```c++
186 using ::testing::HasSubstr;
187 using ::testing::MatchesRegex;
188 ...
189 ASSERT_THAT(foo_string, HasSubstr("needle"));
190 EXPECT_THAT(bar_string, MatchesRegex("\\w*\\d+"));
191 ```
192
193 ### Windows HRESULT assertions
194
195 See [Windows HRESULT Assertions](reference/assertions.md#HRESULT) in the
196 Assertions Reference.
197
198 ### Type Assertions
199
200 You can call the function
201
202 ```c++
203 ::testing::StaticAssertTypeEq<T1, T2>();
204 ```
205
206 to assert that types `T1` and `T2` are the same. The function does nothing if
207 the assertion is satisfied. If the types are different, the function call will
208 fail to compile, the compiler error message will say that `T1 and T2 are not the
209 same type` and most likely (depending on the compiler) show you the actual
210 values of `T1` and `T2`. This is mainly useful inside template code.
211
212 **Caveat**: When used inside a member function of a class template or a function
213 template, `StaticAssertTypeEq<T1, T2>()` is effective only if the function is
214 instantiated. For example, given:
215
216 ```c++
217 template <typename T> class Foo {
218 public:
219 void Bar() { testing::StaticAssertTypeEq<int, T>(); }
220 };
221 ```
222
223 the code:
224
225 ```c++
226 void Test1() { Foo<bool> foo; }
227 ```
228
229 will not generate a compiler error, as `Foo<bool>::Bar()` is never actually
230 instantiated. Instead, you need:
231
232 ```c++
233 void Test2() { Foo<bool> foo; foo.Bar(); }
234 ```
235
236 to cause a compiler error.
237
238 ### Assertion Placement
239
240 You can use assertions in any C++ function. In particular, it doesn't have to be
241 a method of the test fixture class. The one constraint is that assertions that
242 generate a fatal failure (`FAIL*` and `ASSERT_*`) can only be used in
243 void-returning functions. This is a consequence of Google's not using
244 exceptions. By placing it in a non-void function you'll get a confusing compile
245 error like `"error: void value not ignored as it ought to be"` or `"cannot
246 initialize return object of type 'bool' with an rvalue of type 'void'"` or
247 `"error: no viable conversion from 'void' to 'string'"`.
248
249 If you need to use fatal assertions in a function that returns non-void, one
250 option is to make the function return the value in an out parameter instead. For
251 example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You
252 need to make sure that `*result` contains some sensible value even when the
253 function returns prematurely. As the function now returns `void`, you can use
254 any assertion inside of it.
255
256 If changing the function's type is not an option, you should just use assertions
257 that generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`.
258
259 {: .callout .note}
260 NOTE: Constructors and destructors are not considered void-returning functions,
261 according to the C++ language specification, and so you may not use fatal
262 assertions in them; you'll get a compilation error if you try. Instead, either
263 call `abort` and crash the entire test executable, or put the fatal assertion in
264 a `SetUp`/`TearDown` function; see
265 [constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp)
266
267 {: .callout .warning}
268 WARNING: A fatal assertion in a helper function (private void-returning method)
269 called from a constructor or destructor does not terminate the current test, as
270 your intuition might suggest: it merely returns from the constructor or
271 destructor early, possibly leaving your object in a partially-constructed or
272 partially-destructed state! You almost certainly want to `abort` or use
273 `SetUp`/`TearDown` instead.
274
275 ## Skipping test execution
276
277 Related to the assertions `SUCCEED()` and `FAIL()`, you can prevent further test
278 execution at runtime with the `GTEST_SKIP()` macro. This is useful when you need
279 to check for preconditions of the system under test during runtime and skip
280 tests in a meaningful way.
281
282 `GTEST_SKIP()` can be used in individual test cases or in the `SetUp()` methods
283 of classes derived from either `::testing::Environment` or `::testing::Test`.
284 For example:
285
286 ```c++
287 TEST(SkipTest, DoesSkip) {
288 GTEST_SKIP() << "Skipping single test";
289 FAIL(); // Won't fail; it won't be executed
290 }
291
292 class SkipFixture : public ::testing::Test {
293 protected:
294 void SetUp() override {
295 GTEST_SKIP() << "Skipping all tests for this fixture";
296 }
297 };
298
299 // Tests for SkipFixture won't be executed.
300 TEST_F(SkipFixture, SkipsOneTest) {
301 FAIL(); // Won't fail; it won't be executed
302 }
303 ```
304
305 As with assertion macros, you can stream a custom message into `GTEST_SKIP()`.
306
307 ## Teaching GoogleTest How to Print Your Values
308
309 When a test assertion such as `EXPECT_EQ` fails, GoogleTest prints the argument
310 values to help you debug. It does this using a user-extensible value printer.
311
312 This printer knows how to print built-in C++ types, native arrays, STL
313 containers, and any type that supports the `<<` operator. For other types, it
314 prints the raw bytes in the value and hopes that you the user can figure it out.
315
316 As mentioned earlier, the printer is *extensible*. That means you can teach it
317 to do a better job at printing your particular type than to dump the bytes. To
318 do that, define an `AbslStringify()` overload as a `friend` function template
319 for your type:
320
321 ```cpp
322 namespace foo {
323
324 class Point { // We want GoogleTest to be able to print instances of this.
325 ...
326 // Provide a friend overload.
327 template <typename Sink>
328 friend void AbslStringify(Sink& sink, const Point& point) {
329 absl::Format(&sink, "(%d, %d)", point.x, point.y);
330 }
331
332 int x;
333 int y;
334 };
335
336 // If you can't declare the function in the class it's important that the
337 // AbslStringify overload is defined in the SAME namespace that defines Point.
338 // C++'s look-up rules rely on that.
339 enum class EnumWithStringify { kMany = 0, kChoices = 1 };
340
341 template <typename Sink>
342 void AbslStringify(Sink& sink, EnumWithStringify e) {
343 absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices");
344 }
345
346 } // namespace foo
347 ```
348
349 {: .callout .note}
350 Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its
351 string. For more information about supported operations on `AbslStringify()`'s
352 sink, see go/abslstringify.
353
354 `AbslStringify()` can also use `absl::StrFormat`'s catch-all `%v` type specifier
355 within its own format strings to perform type deduction. `Point` above could be
356 formatted as `"(%v, %v)"` for example, and deduce the `int` values as `%d`.
357
358 Sometimes, `AbslStringify()` might not be an option: your team may wish to print
359 types with extra debugging information for testing purposes only. If so, you can
360 instead define a `PrintTo()` function like this:
361
362 ```c++
363 #include <ostream>
364
365 namespace foo {
366
367 class Point {
368 ...
369 friend void PrintTo(const Point& point, std::ostream* os) {
370 *os << "(" << point.x << "," << point.y << ")";
371 }
372
373 int x;
374 int y;
375 };
376
377 // If you can't declare the function in the class it's important that PrintTo()
378 // is defined in the SAME namespace that defines Point. C++'s look-up rules
379 // rely on that.
380 void PrintTo(const Point& point, std::ostream* os) {
381 *os << "(" << point.x << "," << point.y << ")";
382 }
383
384 } // namespace foo
385 ```
386
387 If you have defined both `AbslStringify()` and `PrintTo()`, the latter will be
388 used by GoogleTest. This allows you to customize how the value appears in
389 GoogleTest's output without affecting code that relies on the behavior of
390 `AbslStringify()`.
391
392 If you have an existing `<<` operator and would like to define an
393 `AbslStringify()`, the latter will be used for GoogleTest printing.
394
395 If you want to print a value `x` using GoogleTest's value printer yourself, just
396 call `::testing::PrintToString(x)`, which returns an `std::string`:
397
398 ```c++
399 vector<pair<Point, int> > point_ints = GetPointIntVector();
400
401 EXPECT_TRUE(IsCorrectPointIntVector(point_ints))
402 << "point_ints = " << testing::PrintToString(point_ints);
403 ```
404
405 For more details regarding `AbslStringify()` and its integration with other
406 libraries, see go/abslstringify.
407
408 ## Regular Expression Syntax
409
410 When built with Bazel and using Abseil, GoogleTest uses the
411 [RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX
412 systems (Linux, Cygwin, Mac), GoogleTest uses the
413 [POSIX extended regular expression](https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
414 syntax. To learn about POSIX syntax, you may want to read this
415 [Wikipedia entry](https://en.wikipedia.org/wiki/Regular_expression#POSIX_extended).
416
417 On Windows, GoogleTest uses its own simple regular expression implementation. It
418 lacks many features. For example, we don't support union (`"x|y"`), grouping
419 (`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among
420 others. Below is what we do support (`A` denotes a literal character, period
421 (`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular
422 expressions.):
423
424 Expression | Meaning
425 ---------- | --------------------------------------------------------------
426 `c` | matches any literal character `c`
427 `\\d` | matches any decimal digit
428 `\\D` | matches any character that's not a decimal digit
429 `\\f` | matches `\f`
430 `\\n` | matches `\n`
431 `\\r` | matches `\r`
432 `\\s` | matches any ASCII whitespace, including `\n`
433 `\\S` | matches any character that's not a whitespace
434 `\\t` | matches `\t`
435 `\\v` | matches `\v`
436 `\\w` | matches any letter, `_`, or decimal digit
437 `\\W` | matches any character that `\\w` doesn't match
438 `\\c` | matches any literal character `c`, which must be a punctuation
439 `.` | matches any single character except `\n`
440 `A?` | matches 0 or 1 occurrences of `A`
441 `A*` | matches 0 or many occurrences of `A`
442 `A+` | matches 1 or many occurrences of `A`
443 `^` | matches the beginning of a string (not that of each line)
444 `$` | matches the end of a string (not that of each line)
445 `xy` | matches `x` followed by `y`
446
447 To help you determine which capability is available on your system, GoogleTest
448 defines macros to govern which regular expression it is using. The macros are:
449 `GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death
450 tests to work in all cases, you can either `#if` on these macros or use the more
451 limited syntax only.
452
453 ## Death Tests
454
455 In many applications, there are assertions that can cause application failure if
456 a condition is not met. These consistency checks, which ensure that the program
457 is in a known good state, are there to fail at the earliest possible time after
458 some program state is corrupted. If the assertion checks the wrong condition,
459 then the program may proceed in an erroneous state, which could lead to memory
460 corruption, security holes, or worse. Hence it is vitally important to test that
461 such assertion statements work as expected.
462
463 Since these precondition checks cause the processes to die, we call such tests
464 *death tests*. More generally, any test that checks that a program terminates
465 (except by throwing an exception) in an expected fashion is also a death test.
466
467 Note that if a piece of code throws an exception, we don't consider it "death"
468 for the purpose of death tests, as the caller of the code could catch the
469 exception and avoid the crash. If you want to verify exceptions thrown by your
470 code, see [Exception Assertions](#ExceptionAssertions).
471
472 If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see
473 ["Catching" Failures](#catching-failures).
474
475 ### How to Write a Death Test
476
477 GoogleTest provides assertion macros to support death tests. See
478 [Death Assertions](reference/assertions.md#death) in the Assertions Reference
479 for details.
480
481 To write a death test, simply use one of the macros inside your test function.
482 For example,
483
484 ```c++
485 TEST(MyDeathTest, Foo) {
486 // This death test uses a compound statement.
487 ASSERT_DEATH({
488 int n = 5;
489 Foo(&n);
490 }, "Error on line .* of Foo()");
491 }
492
493 TEST(MyDeathTest, NormalExit) {
494 EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success");
495 }
496
497 TEST(MyDeathTest, KillProcess) {
498 EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL),
499 "Sending myself unblockable signal");
500 }
501 ```
502
503 verifies that:
504
505 * calling `Foo(5)` causes the process to die with the given error message,
506 * calling `NormalExit()` causes the process to print `"Success"` to stderr and
507 exit with exit code 0, and
508 * calling `KillProcess()` kills the process with signal `SIGKILL`.
509
510 {: .callout .warning}
511 Warning: If your death test contains mocks and is expecting a specific exit
512 code, then you must allow the mock objects to be leaked via `Mock::AllowLeak`.
513 This is because the mock leak detector will exit with its own error code if it
514 detects a leak.
515
516 The test function body may contain other assertions and statements as well, if
517 necessary.
518
519 Note that a death test only cares about three things:
520
521 1. does `statement` abort or exit the process?
522 2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status
523 satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`)
524 is the exit status non-zero? And
525 3. does the stderr output match `matcher`?
526
527 In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it
528 will **not** cause the death test to fail, as GoogleTest assertions don't abort
529 the process.
530
531 ### Death Test Naming
532
533 {: .callout .important}
534 IMPORTANT: We strongly recommend you to follow the convention of naming your
535 **test suite** (not test) `*DeathTest` when it contains a death test, as
536 demonstrated in the above example. The
537 [Death Tests And Threads](#death-tests-and-threads) section below explains why.
538
539 If a test fixture class is shared by normal tests and death tests, you can use
540 `using` or `typedef` to introduce an alias for the fixture class and avoid
541 duplicating its code:
542
543 ```c++
544 class FooTest : public testing::Test { ... };
545
546 using FooDeathTest = FooTest;
547
548 TEST_F(FooTest, DoesThis) {
549 // normal test
550 }
551
552 TEST_F(FooDeathTest, DoesThat) {
553 // death test
554 }
555 ```
556
557 ### How It Works
558
559 See [Death Assertions](reference/assertions.md#death) in the Assertions
560 Reference.
561
562 ### Death Tests And Threads
563
564 The reason for the two death test styles has to do with thread safety. Due to
565 well-known problems with forking in the presence of threads, death tests should
566 be run in a single-threaded context. Sometimes, however, it isn't feasible to
567 arrange that kind of environment. For example, statically-initialized modules
568 may start threads before main is ever reached. Once threads have been created,
569 it may be difficult or impossible to clean them up.
570
571 GoogleTest has three features intended to raise awareness of threading issues.
572
573 1. A warning is emitted if multiple threads are running when a death test is
574 encountered.
575 2. Test suites with a name ending in "DeathTest" are run before all other
576 tests.
577 3. It uses `clone()` instead of `fork()` to spawn the child process on Linux
578 (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely
579 to cause the child to hang when the parent process has multiple threads.
580
581 It's perfectly fine to create threads inside a death test statement; they are
582 executed in a separate process and cannot affect the parent.
583
584 ### Death Test Styles
585
586 The "threadsafe" death test style was introduced in order to help mitigate the
587 risks of testing in a possibly multithreaded environment. It trades increased
588 test execution time (potentially dramatically so) for improved thread safety.
589
590 The automated testing framework does not set the style flag. You can choose a
591 particular style of death tests by setting the flag programmatically:
592
593 ```c++
594 GTEST_FLAG_SET(death_test_style, "threadsafe");
595 ```
596
597 You can do this in `main()` to set the style for all death tests in the binary,
598 or in individual tests. Recall that flags are saved before running each test and
599 restored afterwards, so you need not do that yourself. For example:
600
601 ```c++
602 int main(int argc, char** argv) {
603 testing::InitGoogleTest(&argc, argv);
604 GTEST_FLAG_SET(death_test_style, "fast");
605 return RUN_ALL_TESTS();
606 }
607
608 TEST(MyDeathTest, TestOne) {
609 GTEST_FLAG_SET(death_test_style, "threadsafe");
610 // This test is run in the "threadsafe" style:
611 ASSERT_DEATH(ThisShouldDie(), "");
612 }
613
614 TEST(MyDeathTest, TestTwo) {
615 // This test is run in the "fast" style:
616 ASSERT_DEATH(ThisShouldDie(), "");
617 }
618 ```
619
620 ### Caveats
621
622 The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If
623 it leaves the current function via a `return` statement or by throwing an
624 exception, the death test is considered to have failed. Some GoogleTest macros
625 may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid
626 them in `statement`.
627
628 Since `statement` runs in the child process, any in-memory side effect (e.g.
629 modifying a variable, releasing memory, etc) it causes will *not* be observable
630 in the parent process. In particular, if you release memory in a death test,
631 your program will fail the heap check as the parent process will never see the
632 memory reclaimed. To solve this problem, you can
633
634 1. try not to free memory in a death test;
635 2. free the memory again in the parent process; or
636 3. do not use the heap checker in your program.
637
638 Due to an implementation detail, you cannot place multiple death test assertions
639 on the same line; otherwise, compilation will fail with an unobvious error
640 message.
641
642 Despite the improved thread safety afforded by the "threadsafe" style of death
643 test, thread problems such as deadlock are still possible in the presence of
644 handlers registered with `pthread_atfork(3)`.
645
646 ## Using Assertions in Sub-routines
647
648 {: .callout .note}
649 Note: If you want to put a series of test assertions in a subroutine to check
650 for a complex condition, consider using
651 [a custom GMock matcher](gmock_cook_book.md#NewMatchers) instead. This lets you
652 provide a more readable error message in case of failure and avoid all of the
653 issues described below.
654
655 ### Adding Traces to Assertions
656
657 If a test sub-routine is called from several places, when an assertion inside it
658 fails, it can be hard to tell which invocation of the sub-routine the failure is
659 from. You can alleviate this problem using extra logging or custom failure
660 messages, but that usually clutters up your tests. A better solution is to use
661 the `SCOPED_TRACE` macro or the `ScopedTrace` utility:
662
663 ```c++
664 SCOPED_TRACE(message);
665 ```
666
667 ```c++
668 ScopedTrace trace("file_path", line_number, message);
669 ```
670
671 where `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE`
672 macro will cause the current file name, line number, and the given message to be
673 added in every failure message. `ScopedTrace` accepts explicit file name and
674 line number in arguments, which is useful for writing test helpers. The effect
675 will be undone when the control leaves the current lexical scope.
676
677 For example,
678
679 ```c++
680 10: void Sub1(int n) {
681 11: EXPECT_EQ(Bar(n), 1);
682 12: EXPECT_EQ(Bar(n + 1), 2);
683 13: }
684 14:
685 15: TEST(FooTest, Bar) {
686 16: {
687 17: SCOPED_TRACE("A"); // This trace point will be included in
688 18: // every failure in this scope.
689 19: Sub1(1);
690 20: }
691 21: // Now it won't.
692 22: Sub1(9);
693 23: }
694 ```
695
696 could result in messages like these:
697
698 ```none
699 path/to/foo_test.cc:11: Failure
700 Value of: Bar(n)
701 Expected: 1
702 Actual: 2
703 Google Test trace:
704 path/to/foo_test.cc:17: A
705
706 path/to/foo_test.cc:12: Failure
707 Value of: Bar(n + 1)
708 Expected: 2
709 Actual: 3
710 ```
711
712 Without the trace, it would've been difficult to know which invocation of
713 `Sub1()` the two failures come from respectively. (You could add an extra
714 message to each assertion in `Sub1()` to indicate the value of `n`, but that's
715 tedious.)
716
717 Some tips on using `SCOPED_TRACE`:
718
719 1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the
720 beginning of a sub-routine, instead of at each call site.
721 2. When calling sub-routines inside a loop, make the loop iterator part of the
722 message in `SCOPED_TRACE` such that you can know which iteration the failure
723 is from.
724 3. Sometimes the line number of the trace point is enough for identifying the
725 particular invocation of a sub-routine. In this case, you don't have to
726 choose a unique message for `SCOPED_TRACE`. You can simply use `""`.
727 4. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer
728 scope. In this case, all active trace points will be included in the failure
729 messages, in reverse order they are encountered.
730 5. The trace dump is clickable in Emacs - hit `return` on a line number and
731 you'll be taken to that line in the source file!
732
733 ### Propagating Fatal Failures
734
735 A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that
736 when they fail they only abort the *current function*, not the entire test. For
737 example, the following test will segfault:
738
739 ```c++
740 void Subroutine() {
741 // Generates a fatal failure and aborts the current function.
742 ASSERT_EQ(1, 2);
743
744 // The following won't be executed.
745 ...
746 }
747
748 TEST(FooTest, Bar) {
749 Subroutine(); // The intended behavior is for the fatal failure
750 // in Subroutine() to abort the entire test.
751
752 // The actual behavior: the function goes on after Subroutine() returns.
753 int* p = nullptr;
754 *p = 3; // Segfault!
755 }
756 ```
757
758 To alleviate this, GoogleTest provides three different solutions. You could use
759 either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
760 `HasFatalFailure()` function. They are described in the following two
761 subsections.
762
763 #### Asserting on Subroutines with an exception
764
765 The following code can turn ASSERT-failure into an exception:
766
767 ```c++
768 class ThrowListener : public testing::EmptyTestEventListener {
769 void OnTestPartResult(const testing::TestPartResult& result) override {
770 if (result.type() == testing::TestPartResult::kFatalFailure) {
771 throw testing::AssertionException(result);
772 }
773 }
774 };
775 int main(int argc, char** argv) {
776 ...
777 testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener);
778 return RUN_ALL_TESTS();
779 }
780 ```
781
782 This listener should be added after other listeners if you have any, otherwise
783 they won't see failed `OnTestPartResult`.
784
785 #### Asserting on Subroutines
786
787 As shown above, if your test calls a subroutine that has an `ASSERT_*` failure
788 in it, the test will continue after the subroutine returns. This may not be what
789 you want.
790
791 Often people want fatal failures to propagate like exceptions. For that
792 GoogleTest offers the following macros:
793
794 Fatal assertion | Nonfatal assertion | Verifies
795 ------------------------------------- | ------------------------------------- | --------
796 `ASSERT_NO_FATAL_FAILURE(statement);` | `EXPECT_NO_FATAL_FAILURE(statement);` | `statement` doesn't generate any new fatal failures in the current thread.
797
798 Only failures in the thread that executes the assertion are checked to determine
799 the result of this type of assertions. If `statement` creates new threads,
800 failures in these threads are ignored.
801
802 Examples:
803
804 ```c++
805 ASSERT_NO_FATAL_FAILURE(Foo());
806
807 int i;
808 EXPECT_NO_FATAL_FAILURE({
809 i = Bar();
810 });
811 ```
812
813 Assertions from multiple threads are currently not supported on Windows.
814
815 #### Checking for Failures in the Current Test
816
817 `HasFatalFailure()` in the `::testing::Test` class returns `true` if an
818 assertion in the current test has suffered a fatal failure. This allows
819 functions to catch fatal failures in a sub-routine and return early.
820
821 ```c++
822 class Test {
823 public:
824 ...
825 static bool HasFatalFailure();
826 };
827 ```
828
829 The typical usage, which basically simulates the behavior of a thrown exception,
830 is:
831
832 ```c++
833 TEST(FooTest, Bar) {
834 Subroutine();
835 // Aborts if Subroutine() had a fatal failure.
836 if (HasFatalFailure()) return;
837
838 // The following won't be executed.
839 ...
840 }
841 ```
842
843 If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test
844 fixture, you must add the `::testing::Test::` prefix, as in:
845
846 ```c++
847 if (testing::Test::HasFatalFailure()) return;
848 ```
849
850 Similarly, `HasNonfatalFailure()` returns `true` if the current test has at
851 least one non-fatal failure, and `HasFailure()` returns `true` if the current
852 test has at least one failure of either kind.
853
854 ## Logging Additional Information
855
856 In your test code, you can call `RecordProperty("key", value)` to log additional
857 information, where `value` can be either a string or an `int`. The *last* value
858 recorded for a key will be emitted to the
859 [XML output](#generating-an-xml-report) if you specify one. For example, the
860 test
861
862 ```c++
863 TEST_F(WidgetUsageTest, MinAndMaxWidgets) {
864 RecordProperty("MaximumWidgets", ComputeMaxUsage());
865 RecordProperty("MinimumWidgets", ComputeMinUsage());
866 }
867 ```
868
869 will output XML like this:
870
871 ```xml
872 ...
873 <testcase name="MinAndMaxWidgets" file="test.cpp" line="1" status="run" time="0.006" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" />
874 ...
875 ```
876
877 {: .callout .note}
878 > NOTE:
879 >
880 > * `RecordProperty()` is a static member of the `Test` class. Therefore it
881 > needs to be prefixed with `::testing::Test::` if used outside of the
882 > `TEST` body and the test fixture class.
883 > * *`key`* must be a valid XML attribute name, and cannot conflict with the
884 > ones already used by GoogleTest (`name`, `status`, `time`, `classname`,
885 > `type_param`, and `value_param`).
886 > * Calling `RecordProperty()` outside of the lifespan of a test is allowed.
887 > If it's called outside of a test but between a test suite's
888 > `SetUpTestSuite()` and `TearDownTestSuite()` methods, it will be
889 > attributed to the XML element for the test suite. If it's called outside
890 > of all test suites (e.g. in a test environment), it will be attributed to
891 > the top-level XML element.
892
893 ## Sharing Resources Between Tests in the Same Test Suite
894
895 GoogleTest creates a new test fixture object for each test in order to make
896 tests independent and easier to debug. However, sometimes tests use resources
897 that are expensive to set up, making the one-copy-per-test model prohibitively
898 expensive.
899
900 If the tests don't change the resource, there's no harm in their sharing a
901 single resource copy. So, in addition to per-test set-up/tear-down, GoogleTest
902 also supports per-test-suite set-up/tear-down. To use it:
903
904 1. In your test fixture class (say `FooTest` ), declare as `static` some member
905 variables to hold the shared resources.
906 2. Outside your test fixture class (typically just below it), define those
907 member variables, optionally giving them initial values.
908 3. In the same test fixture class, define a public member function `static void
909 SetUpTestSuite()` (remember not to spell it as **`SetupTestSuite`** with a
910 small `u`!) to set up the shared resources and a `static void
911 TearDownTestSuite()` function to tear them down.
912
913 That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the
914 *first test* in the `FooTest` test suite (i.e. before creating the first
915 `FooTest` object), and calls `TearDownTestSuite()` after running the *last test*
916 in it (i.e. after deleting the last `FooTest` object). In between, the tests can
917 use the shared resources.
918
919 Remember that the test order is undefined, so your code can't depend on a test
920 preceding or following another. Also, the tests must either not modify the state
921 of any shared resource, or, if they do modify the state, they must restore the
922 state to its original value before passing control to the next test.
923
924 Note that `SetUpTestSuite()` may be called multiple times for a test fixture
925 class that has derived classes, so you should not expect code in the function
926 body to be run only once. Also, derived classes still have access to shared
927 resources defined as static members, so careful consideration is needed when
928 managing shared resources to avoid memory leaks if shared resources are not
929 properly cleaned up in `TearDownTestSuite()`.
930
931 Here's an example of per-test-suite set-up and tear-down:
932
933 ```c++
934 class FooTest : public testing::Test {
935 protected:
936 // Per-test-suite set-up.
937 // Called before the first test in this test suite.
938 // Can be omitted if not needed.
939 static void SetUpTestSuite() {
940 shared_resource_ = new ...;
941
942 // If `shared_resource_` is **not deleted** in `TearDownTestSuite()`,
943 // reallocation should be prevented because `SetUpTestSuite()` may be called
944 // in subclasses of FooTest and lead to memory leak.
945 //
946 // if (shared_resource_ == nullptr) {
947 // shared_resource_ = new ...;
948 // }
949 }
950
951 // Per-test-suite tear-down.
952 // Called after the last test in this test suite.
953 // Can be omitted if not needed.
954 static void TearDownTestSuite() {
955 delete shared_resource_;
956 shared_resource_ = nullptr;
957 }
958
959 // You can define per-test set-up logic as usual.
960 void SetUp() override { ... }
961
962 // You can define per-test tear-down logic as usual.
963 void TearDown() override { ... }
964
965 // Some expensive resource shared by all tests.
966 static T* shared_resource_;
967 };
968
969 T* FooTest::shared_resource_ = nullptr;
970
971 TEST_F(FooTest, Test1) {
972 ... you can refer to shared_resource_ here ...
973 }
974
975 TEST_F(FooTest, Test2) {
976 ... you can refer to shared_resource_ here ...
977 }
978 ```
979
980 {: .callout .note}
981 NOTE: Though the above code declares `SetUpTestSuite()` protected, it may
982 sometimes be necessary to declare it public, such as when using it with
983 `TEST_P`.
984
985 ## Global Set-Up and Tear-Down
986
987 Just as you can do set-up and tear-down at the test level and the test suite
988 level, you can also do it at the test program level. Here's how.
989
990 First, you subclass the `::testing::Environment` class to define a test
991 environment, which knows how to set-up and tear-down:
992
993 ```c++
994 class Environment : public ::testing::Environment {
995 public:
996 ~Environment() override {}
997
998 // Override this to define how to set up the environment.
999 void SetUp() override {}
1000
1001 // Override this to define how to tear down the environment.
1002 void TearDown() override {}
1003 };
1004 ```
1005
1006 Then, you register an instance of your environment class with GoogleTest by
1007 calling the `::testing::AddGlobalTestEnvironment()` function:
1008
1009 ```c++
1010 Environment* AddGlobalTestEnvironment(Environment* env);
1011 ```
1012
1013 Now, when `RUN_ALL_TESTS()` is invoked, it first calls the `SetUp()` method. The
1014 tests are then executed, provided that none of the environments have reported
1015 fatal failures and `GTEST_SKIP()` has not been invoked. Finally, `TearDown()` is
1016 called.
1017
1018 Note that `SetUp()` and `TearDown()` are only invoked if there is at least one
1019 test to be performed. Importantly, `TearDown()` is executed even if the test is
1020 not run due to a fatal failure or `GTEST_SKIP()`.
1021
1022 Calling `SetUp()` and `TearDown()` for each iteration depends on the flag
1023 `gtest_recreate_environments_when_repeating`. `SetUp()` and `TearDown()` are
1024 called for each environment object when the object is recreated for each
1025 iteration. However, if test environments are not recreated for each iteration,
1026 `SetUp()` is called only on the first iteration, and `TearDown()` is called only
1027 on the last iteration.
1028
1029 It's OK to register multiple environment objects. In this suite, their `SetUp()`
1030 will be called in the order they are registered, and their `TearDown()` will be
1031 called in the reverse order.
1032
1033 Note that GoogleTest takes ownership of the registered environment objects.
1034 Therefore **do not delete them** by yourself.
1035
1036 You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called,
1037 probably in `main()`. If you use `gtest_main`, you need to call this before
1038 `main()` starts for it to take effect. One way to do this is to define a global
1039 variable like this:
1040
1041 ```c++
1042 testing::Environment* const foo_env =
1043 testing::AddGlobalTestEnvironment(new FooEnvironment);
1044 ```
1045
1046 However, we strongly recommend you to write your own `main()` and call
1047 `AddGlobalTestEnvironment()` there, as relying on initialization of global
1048 variables makes the code harder to read and may cause problems when you register
1049 multiple environments from different translation units and the environments have
1050 dependencies among them (remember that the compiler doesn't guarantee the order
1051 in which global variables from different translation units are initialized).
1052
1053 ## Value-Parameterized Tests
1054
1055 *Value-parameterized tests* allow you to test your code with different
1056 parameters without writing multiple copies of the same test. This is useful in a
1057 number of situations, for example:
1058
1059 * You have a piece of code whose behavior is affected by one or more
1060 command-line flags. You want to make sure your code performs correctly for
1061 various values of those flags.
1062 * You want to test different implementations of an OO interface.
1063 * You want to test your code over various inputs (a.k.a. data-driven testing).
1064 This feature is easy to abuse, so please exercise your good sense when doing
1065 it!
1066
1067 ### How to Write Value-Parameterized Tests
1068
1069 To write value-parameterized tests, first you should define a fixture class. It
1070 must be derived from both `testing::Test` and `testing::WithParamInterface<T>`
1071 (the latter is a pure interface), where `T` is the type of your parameter
1072 values. For convenience, you can just derive the fixture class from
1073 `testing::TestWithParam<T>`, which itself is derived from both `testing::Test`
1074 and `testing::WithParamInterface<T>`. `T` can be any copyable type. If it's a
1075 raw pointer, you are responsible for managing the lifespan of the pointed
1076 values.
1077
1078 {: .callout .note}
1079 NOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()`
1080 they must be declared **public** rather than **protected** in order to use
1081 `TEST_P`.
1082
1083 ```c++
1084 class FooTest :
1085 public testing::TestWithParam<absl::string_view> {
1086 // You can implement all the usual fixture class members here.
1087 // To access the test parameter, call GetParam() from class
1088 // TestWithParam<T>.
1089 };
1090
1091 // Or, when you want to add parameters to a pre-existing fixture class:
1092 class BaseTest : public testing::Test {
1093 ...
1094 };
1095 class BarTest : public BaseTest,
1096 public testing::WithParamInterface<absl::string_view> {
1097 ...
1098 };
1099 ```
1100
1101 Then, use the `TEST_P` macro to define as many test patterns using this fixture
1102 as you want. The `_P` suffix is for "parameterized" or "pattern", whichever you
1103 prefer to think.
1104
1105 ```c++
1106 TEST_P(FooTest, DoesBlah) {
1107 // Inside a test, access the test parameter with the GetParam() method
1108 // of the TestWithParam<T> class:
1109 EXPECT_TRUE(foo.Blah(GetParam()));
1110 ...
1111 }
1112
1113 TEST_P(FooTest, HasBlahBlah) {
1114 ...
1115 }
1116 ```
1117
1118 Finally, you can use the `INSTANTIATE_TEST_SUITE_P` macro to instantiate the
1119 test suite with any set of parameters you want. GoogleTest defines a number of
1120 functions for generating test parameters—see details at
1121 [`INSTANTIATE_TEST_SUITE_P`](reference/testing.md#INSTANTIATE_TEST_SUITE_P) in
1122 the Testing Reference.
1123
1124 For example, the following statement will instantiate tests from the `FooTest`
1125 test suite each with parameter values `"meeny"`, `"miny"`, and `"moe"` using the
1126 [`Values`](reference/testing.md#param-generators) parameter generator:
1127
1128 ```c++
1129 INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe,
1130 FooTest,
1131 testing::Values("meeny", "miny", "moe"));
1132 ```
1133
1134 {: .callout .note}
1135 NOTE: The code above must be placed at global or namespace scope, not at
1136 function scope.
1137
1138 The first argument to `INSTANTIATE_TEST_SUITE_P` is a unique name for the
1139 instantiation of the test suite. The next argument is the name of the test
1140 pattern, and the last is the
1141 [parameter generator](reference/testing.md#param-generators).
1142
1143 The parameter generator expression is not evaluated until GoogleTest is
1144 initialized (via `InitGoogleTest()`). Any prior initialization done in the
1145 `main` function will be accessible from the parameter generator, for example,
1146 the results of flag parsing.
1147
1148 You can instantiate a test pattern more than once, so to distinguish different
1149 instances of the pattern, the instantiation name is added as a prefix to the
1150 actual test suite name. Remember to pick unique prefixes for different
1151 instantiations. The tests from the instantiation above will have these names:
1152
1153 * `MeenyMinyMoe/FooTest.DoesBlah/0` for `"meeny"`
1154 * `MeenyMinyMoe/FooTest.DoesBlah/1` for `"miny"`
1155 * `MeenyMinyMoe/FooTest.DoesBlah/2` for `"moe"`
1156 * `MeenyMinyMoe/FooTest.HasBlahBlah/0` for `"meeny"`
1157 * `MeenyMinyMoe/FooTest.HasBlahBlah/1` for `"miny"`
1158 * `MeenyMinyMoe/FooTest.HasBlahBlah/2` for `"moe"`
1159
1160 You can use these names in [`--gtest_filter`](#running-a-subset-of-the-tests).
1161
1162 The following statement will instantiate all tests from `FooTest` again, each
1163 with parameter values `"cat"` and `"dog"` using the
1164 [`ValuesIn`](reference/testing.md#param-generators) parameter generator:
1165
1166 ```c++
1167 constexpr absl::string_view kPets[] = {"cat", "dog"};
1168 INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets));
1169 ```
1170
1171 The tests from the instantiation above will have these names:
1172
1173 * `Pets/FooTest.DoesBlah/0` for `"cat"`
1174 * `Pets/FooTest.DoesBlah/1` for `"dog"`
1175 * `Pets/FooTest.HasBlahBlah/0` for `"cat"`
1176 * `Pets/FooTest.HasBlahBlah/1` for `"dog"`
1177
1178 Please note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the
1179 given test suite, whether their definitions come before or *after* the
1180 `INSTANTIATE_TEST_SUITE_P` statement.
1181
1182 Additionally, by default, every `TEST_P` without a corresponding
1183 `INSTANTIATE_TEST_SUITE_P` causes a failing test in test suite
1184 `GoogleTestVerification`. If you have a test suite where that omission is not an
1185 error, for example it is in a library that may be linked in for other reasons or
1186 where the list of test cases is dynamic and may be empty, then this check can be
1187 suppressed by tagging the test suite:
1188
1189 ```c++
1190 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest);
1191 ```
1192
1193 You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples.
1194
1195 [sample7_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc "Parameterized Test example"
1196 [sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
1197
1198 ### Creating Value-Parameterized Abstract Tests
1199
1200 In the above, we define and instantiate `FooTest` in the *same* source file.
1201 Sometimes you may want to define value-parameterized tests in a library and let
1202 other people instantiate them later. This pattern is known as *abstract tests*.
1203 As an example of its application, when you are designing an interface you can
1204 write a standard suite of abstract tests (perhaps using a factory function as
1205 the test parameter) that all implementations of the interface are expected to
1206 pass. When someone implements the interface, they can instantiate your suite to
1207 get all the interface-conformance tests for free.
1208
1209 To define abstract tests, you should organize your code like this:
1210
1211 1. Put the definition of the parameterized test fixture class (e.g. `FooTest`)
1212 in a header file, say `foo_param_test.h`. Think of this as *declaring* your
1213 abstract tests.
1214 2. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes
1215 `foo_param_test.h`. Think of this as *implementing* your abstract tests.
1216
1217 Once they are defined, you can instantiate them by including `foo_param_test.h`,
1218 invoking `INSTANTIATE_TEST_SUITE_P()`, and depending on the library target that
1219 contains `foo_param_test.cc`. You can instantiate the same abstract test suite
1220 multiple times, possibly in different source files.
1221
1222 ### Specifying Names for Value-Parameterized Test Parameters
1223
1224 The optional last argument to `INSTANTIATE_TEST_SUITE_P()` allows the user to
1225 specify a function or functor that generates custom test name suffixes based on
1226 the test parameters. The function should accept one argument of type
1227 `testing::TestParamInfo<class ParamType>`, and return `std::string`.
1228
1229 `testing::PrintToStringParamName` is a builtin test suffix generator that
1230 returns the value of `testing::PrintToString(GetParam())`. It does not work for
1231 `std::string` or C strings.
1232
1233 {: .callout .note}
1234 NOTE: test names must be non-empty, unique, and may only contain ASCII
1235 alphanumeric characters. In particular, they
1236 [should not contain underscores](faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore)
1237
1238 ```c++
1239 class MyTestSuite : public testing::TestWithParam<int> {};
1240
1241 TEST_P(MyTestSuite, MyTest)
1242 {
1243 std::cout << "Example Test Param: " << GetParam() << std::endl;
1244 }
1245
1246 INSTANTIATE_TEST_SUITE_P(MyGroup, MyTestSuite, testing::Range(0, 10),
1247 testing::PrintToStringParamName());
1248 ```
1249
1250 Providing a custom functor allows for more control over test parameter name
1251 generation, especially for types where the automatic conversion does not
1252 generate helpful parameter names (e.g. strings as demonstrated above). The
1253 following example illustrates this for multiple parameters, an enumeration type
1254 and a string, and also demonstrates how to combine generators. It uses a lambda
1255 for conciseness:
1256
1257 ```c++
1258 enum class MyType { MY_FOO = 0, MY_BAR = 1 };
1259
1260 class MyTestSuite : public testing::TestWithParam<std::tuple<MyType, std::string>> {
1261 };
1262
1263 INSTANTIATE_TEST_SUITE_P(
1264 MyGroup, MyTestSuite,
1265 testing::Combine(
1266 testing::Values(MyType::MY_FOO, MyType::MY_BAR),
1267 testing::Values("A", "B")),
1268 [](const testing::TestParamInfo<MyTestSuite::ParamType>& info) {
1269 std::string name = absl::StrCat(
1270 std::get<0>(info.param) == MyType::MY_FOO ? "Foo" : "Bar",
1271 std::get<1>(info.param));
1272 absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_');
1273 return name;
1274 });
1275 ```
1276
1277 ## Typed Tests
1278
1279 Suppose you have multiple implementations of the same interface and want to make
1280 sure that all of them satisfy some common requirements. Or, you may have defined
1281 several types that are supposed to conform to the same "concept" and you want to
1282 verify it. In both cases, you want the same test logic repeated for different
1283 types.
1284
1285 While you can write one `TEST` or `TEST_F` for each type you want to test (and
1286 you may even factor the test logic into a function template that you invoke from
1287 the `TEST`), it's tedious and doesn't scale: if you want `m` tests over `n`
1288 types, you'll end up writing `m*n` `TEST`s.
1289
1290 *Typed tests* allow you to repeat the same test logic over a list of types. You
1291 only need to write the test logic once, although you must know the type list
1292 when writing typed tests. Here's how you do it:
1293
1294 First, define a fixture class template. It should be parameterized by a type.
1295 Remember to derive it from `::testing::Test`:
1296
1297 ```c++
1298 template <typename T>
1299 class FooTest : public testing::Test {
1300 public:
1301 ...
1302 using List = std::list<T>;
1303 static T shared_;
1304 T value_;
1305 };
1306 ```
1307
1308 Next, associate a list of types with the test suite, which will be repeated for
1309 each type in the list:
1310
1311 ```c++
1312 using MyTypes = ::testing::Types<char, int, unsigned int>;
1313 TYPED_TEST_SUITE(FooTest, MyTypes);
1314 ```
1315
1316 The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE`
1317 macro to parse correctly. Otherwise the compiler will think that each comma in
1318 the type list introduces a new macro argument.
1319
1320 Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this
1321 test suite. You can repeat this as many times as you want:
1322
1323 ```c++
1324 TYPED_TEST(FooTest, DoesBlah) {
1325 // Inside a test, refer to the special name TypeParam to get the type
1326 // parameter. Since we are inside a derived class template, C++ requires
1327 // us to visit the members of FooTest via 'this'.
1328 TypeParam n = this->value_;
1329
1330 // To visit static members of the fixture, add the 'TestFixture::'
1331 // prefix.
1332 n += TestFixture::shared_;
1333
1334 // To refer to typedefs in the fixture, add the 'typename TestFixture::'
1335 // prefix. The 'typename' is required to satisfy the compiler.
1336 typename TestFixture::List values;
1337
1338 values.push_back(n);
1339 ...
1340 }
1341
1342 TYPED_TEST(FooTest, HasPropertyA) { ... }
1343 ```
1344
1345 You can see [sample6_unittest.cc] for a complete example.
1346
1347 [sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example"
1348
1349 ## Type-Parameterized Tests
1350
1351 *Type-parameterized tests* are like typed tests, except that they don't require
1352 you to know the list of types ahead of time. Instead, you can define the test
1353 logic first and instantiate it with different type lists later. You can even
1354 instantiate it more than once in the same program.
1355
1356 If you are designing an interface or concept, you can define a suite of
1357 type-parameterized tests to verify properties that any valid implementation of
1358 the interface/concept should have. Then, the author of each implementation can
1359 just instantiate the test suite with their type to verify that it conforms to
1360 the requirements, without having to write similar tests repeatedly. Here's an
1361 example:
1362
1363 First, define a fixture class template, as we did with typed tests:
1364
1365 ```c++
1366 template <typename T>
1367 class FooTest : public testing::Test {
1368 void DoSomethingInteresting();
1369 ...
1370 };
1371 ```
1372
1373 Next, declare that you will define a type-parameterized test suite:
1374
1375 ```c++
1376 TYPED_TEST_SUITE_P(FooTest);
1377 ```
1378
1379 Then, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat
1380 this as many times as you want:
1381
1382 ```c++
1383 TYPED_TEST_P(FooTest, DoesBlah) {
1384 // Inside a test, refer to TypeParam to get the type parameter.
1385 TypeParam n = 0;
1386
1387 // You will need to use `this` explicitly to refer to fixture members.
1388 this->DoSomethingInteresting()
1389 ...
1390 }
1391
1392 TYPED_TEST_P(FooTest, HasPropertyA) { ... }
1393 ```
1394
1395 Now the tricky part: you need to register all test patterns using the
1396 `REGISTER_TYPED_TEST_SUITE_P` macro before you can instantiate them. The first
1397 argument of the macro is the test suite name; the rest are the names of the
1398 tests in this test suite:
1399
1400 ```c++
1401 REGISTER_TYPED_TEST_SUITE_P(FooTest,
1402 DoesBlah, HasPropertyA);
1403 ```
1404
1405 Finally, you are free to instantiate the pattern with the types you want. If you
1406 put the above code in a header file, you can `#include` it in multiple C++
1407 source files and instantiate it multiple times.
1408
1409 ```c++
1410 using MyTypes = ::testing::Types<char, int, unsigned int>;
1411 INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
1412 ```
1413
1414 To distinguish different instances of the pattern, the first argument to the
1415 `INSTANTIATE_TYPED_TEST_SUITE_P` macro is a prefix that will be added to the
1416 actual test suite name. Remember to pick unique prefixes for different
1417 instances.
1418
1419 In the special case where the type list contains only one type, you can write
1420 that type directly without `::testing::Types<...>`, like this:
1421
1422 ```c++
1423 INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);
1424 ```
1425
1426 You can see [sample6_unittest.cc] for a complete example.
1427
1428 ## Testing Private Code
1429
1430 If you change your software's internal implementation, your tests should not
1431 break as long as the change is not observable by users. Therefore, **per the
1432 black-box testing principle, most of the time you should test your code through
1433 its public interfaces.**
1434
1435 **If you still find yourself needing to test internal implementation code,
1436 consider if there's a better design.** The desire to test internal
1437 implementation is often a sign that the class is doing too much. Consider
1438 extracting an implementation class, and testing it. Then use that implementation
1439 class in the original class.
1440
1441 If you absolutely have to test non-public interface code though, you can. There
1442 are two cases to consider:
1443
1444 * Static functions ( *not* the same as static member functions!) or unnamed
1445 namespaces, and
1446 * Private or protected class members
1447
1448 To test them, we use the following special techniques:
1449
1450 * Both static functions and definitions/declarations in an unnamed namespace
1451 are only visible within the same translation unit. To test them, you can
1452 `#include` the entire `.cc` file being tested in your `*_test.cc` file.
1453 (#including `.cc` files is not a good way to reuse code - you should not do
1454 this in production code!)
1455
1456 However, a better approach is to move the private code into the
1457 `foo::internal` namespace, where `foo` is the namespace your project
1458 normally uses, and put the private declarations in a `*-internal.h` file.
1459 Your production `.cc` files and your tests are allowed to include this
1460 internal header, but your clients are not. This way, you can fully test your
1461 internal implementation without leaking it to your clients.
1462
1463 * Private class members are only accessible from within the class or by
1464 friends. To access a class' private members, you can declare your test
1465 fixture as a friend to the class and define accessors in your fixture. Tests
1466 using the fixture can then access the private members of your production
1467 class via the accessors in the fixture. Note that even though your fixture
1468 is a friend to your production class, your tests are not automatically
1469 friends to it, as they are technically defined in sub-classes of the
1470 fixture.
1471
1472 Another way to test private members is to refactor them into an
1473 implementation class, which is then declared in a `*-internal.h` file. Your
1474 clients aren't allowed to include this header but your tests can. Such is
1475 called the
1476 [Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/)
1477 (Private Implementation) idiom.
1478
1479 Or, you can declare an individual test as a friend of your class by adding
1480 this line in the class body:
1481
1482 ```c++
1483 FRIEND_TEST(TestSuiteName, TestName);
1484 ```
1485
1486 For example,
1487
1488 ```c++
1489 // foo.h
1490 class Foo {
1491 ...
1492 private:
1493 FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
1494
1495 int Bar(void* x);
1496 };
1497
1498 // foo_test.cc
1499 ...
1500 TEST(FooTest, BarReturnsZeroOnNull) {
1501 Foo foo;
1502 EXPECT_EQ(foo.Bar(NULL), 0); // Uses Foo's private member Bar().
1503 }
1504 ```
1505
1506 Pay special attention when your class is defined in a namespace. If you want
1507 your test fixtures and tests to be friends of your class, then they must be
1508 defined in the exact same namespace (no anonymous or inline namespaces).
1509
1510 For example, if the code to be tested looks like:
1511
1512 ```c++
1513 namespace my_namespace {
1514
1515 class Foo {
1516 friend class FooTest;
1517 FRIEND_TEST(FooTest, Bar);
1518 FRIEND_TEST(FooTest, Baz);
1519 ... definition of the class Foo ...
1520 };
1521
1522 } // namespace my_namespace
1523 ```
1524
1525 Your test code should be something like:
1526
1527 ```c++
1528 namespace my_namespace {
1529
1530 class FooTest : public testing::Test {
1531 protected:
1532 ...
1533 };
1534
1535 TEST_F(FooTest, Bar) { ... }
1536 TEST_F(FooTest, Baz) { ... }
1537
1538 } // namespace my_namespace
1539 ```
1540
1541 ## "Catching" Failures
1542
1543 If you are building a testing utility on top of GoogleTest, you'll want to test
1544 your utility. What framework would you use to test it? GoogleTest, of course.
1545
1546 The challenge is to verify that your testing utility reports failures correctly.
1547 In frameworks that report a failure by throwing an exception, you could catch
1548 the exception and assert on it. But GoogleTest doesn't use exceptions, so how do
1549 we test that a piece of code generates an expected failure?
1550
1551 `"gtest/gtest-spi.h"` contains some constructs to do this.
1552 After #including this header, you can use
1553
1554 ```c++
1555 EXPECT_FATAL_FAILURE(statement, substring);
1556 ```
1557
1558 to assert that `statement` generates a fatal (e.g. `ASSERT_*`) failure in the
1559 current thread whose message contains the given `substring`, or use
1560
1561 ```c++
1562 EXPECT_NONFATAL_FAILURE(statement, substring);
1563 ```
1564
1565 if you are expecting a non-fatal (e.g. `EXPECT_*`) failure.
1566
1567 Only failures in the current thread are checked to determine the result of this
1568 type of expectations. If `statement` creates new threads, failures in these
1569 threads are also ignored. If you want to catch failures in other threads as
1570 well, use one of the following macros instead:
1571
1572 ```c++
1573 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substring);
1574 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring);
1575 ```
1576
1577 {: .callout .note}
1578 NOTE: Assertions from multiple threads are currently not supported on Windows.
1579
1580 For technical reasons, there are some caveats:
1581
1582 1. You cannot stream a failure message to either macro.
1583
1584 2. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot reference
1585 local non-static variables or non-static members of `this` object.
1586
1587 3. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot return a
1588 value.
1589
1590 ## Registering tests programmatically
1591
1592 The `TEST` macros handle the vast majority of all use cases, but there are few
1593 where runtime registration logic is required. For those cases, the framework
1594 provides the `::testing::RegisterTest` that allows callers to register arbitrary
1595 tests dynamically.
1596
1597 This is an advanced API only to be used when the `TEST` macros are insufficient.
1598 The macros should be preferred when possible, as they avoid most of the
1599 complexity of calling this function.
1600
1601 It provides the following signature:
1602
1603 ```c++
1604 template <typename Factory>
1605 TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
1606 const char* type_param, const char* value_param,
1607 const char* file, int line, Factory factory);
1608 ```
1609
1610 The `factory` argument is a factory callable (move-constructible) object or
1611 function pointer that creates a new instance of the Test object. It handles
1612 ownership to the caller. The signature of the callable is `Fixture*()`, where
1613 `Fixture` is the test fixture class for the test. All tests registered with the
1614 same `test_suite_name` must return the same fixture type. This is checked at
1615 runtime.
1616
1617 The framework will infer the fixture class from the factory and will call the
1618 `SetUpTestSuite` and `TearDownTestSuite` for it.
1619
1620 Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is
1621 undefined.
1622
1623 Use case example:
1624
1625 ```c++
1626 class MyFixture : public testing::Test {
1627 public:
1628 // All of these optional, just like in regular macro usage.
1629 static void SetUpTestSuite() { ... }
1630 static void TearDownTestSuite() { ... }
1631 void SetUp() override { ... }
1632 void TearDown() override { ... }
1633 };
1634
1635 class MyTest : public MyFixture {
1636 public:
1637 explicit MyTest(int data) : data_(data) {}
1638 void TestBody() override { ... }
1639
1640 private:
1641 int data_;
1642 };
1643
1644 void RegisterMyTests(const std::vector<int>& values) {
1645 for (int v : values) {
1646 testing::RegisterTest(
1647 "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
1648 std::to_string(v).c_str(),
1649 __FILE__, __LINE__,
1650 // Important to use the fixture type as the return type here.
1651 [=]() -> MyFixture* { return new MyTest(v); });
1652 }
1653 }
1654 ...
1655 int main(int argc, char** argv) {
1656 testing::InitGoogleTest(&argc, argv);
1657 std::vector<int> values_to_test = LoadValuesFromConfig();
1658 RegisterMyTests(values_to_test);
1659 ...
1660 return RUN_ALL_TESTS();
1661 }
1662 ```
1663
1664 ## Getting the Current Test's Name
1665
1666 Sometimes a function may need to know the name of the currently running test.
1667 For example, you may be using the `SetUp()` method of your test fixture to set
1668 the golden file name based on which test is running. The
1669 [`TestInfo`](reference/testing.md#TestInfo) class has this information.
1670
1671 To obtain a `TestInfo` object for the currently running test, call
1672 `current_test_info()` on the [`UnitTest`](reference/testing.md#UnitTest)
1673 singleton object:
1674
1675 ```c++
1676 // Gets information about the currently running test.
1677 // Do NOT delete the returned object - it's managed by the UnitTest class.
1678 const testing::TestInfo* const test_info =
1679 testing::UnitTest::GetInstance()->current_test_info();
1680
1681 printf("We are in test %s of test suite %s.\n",
1682 test_info->name(),
1683 test_info->test_suite_name());
1684 ```
1685
1686 `current_test_info()` returns a null pointer if no test is running. In
1687 particular, you cannot find the test suite name in `SetUpTestSuite()`,
1688 `TearDownTestSuite()` (where you know the test suite name implicitly), or
1689 functions called from them.
1690
1691 ## Extending GoogleTest by Handling Test Events
1692
1693 GoogleTest provides an **event listener API** to let you receive notifications
1694 about the progress of a test program and test failures. The events you can
1695 listen to include the start and end of the test program, a test suite, or a test
1696 method, among others. You may use this API to augment or replace the standard
1697 console output, replace the XML output, or provide a completely different form
1698 of output, such as a GUI or a database. You can also use test events as
1699 checkpoints to implement a resource leak checker, for example.
1700
1701 ### Defining Event Listeners
1702
1703 To define a event listener, you subclass either
1704 [`testing::TestEventListener`](reference/testing.md#TestEventListener) or
1705 [`testing::EmptyTestEventListener`](reference/testing.md#EmptyTestEventListener)
1706 The former is an (abstract) interface, where *each pure virtual method can be
1707 overridden to handle a test event* (For example, when a test starts, the
1708 `OnTestStart()` method will be called.). The latter provides an empty
1709 implementation of all methods in the interface, such that a subclass only needs
1710 to override the methods it cares about.
1711
1712 When an event is fired, its context is passed to the handler function as an
1713 argument. The following argument types are used:
1714
1715 * UnitTest reflects the state of the entire test program,
1716 * TestSuite has information about a test suite, which can contain one or more
1717 tests,
1718 * TestInfo contains the state of a test, and
1719 * TestPartResult represents the result of a test assertion.
1720
1721 An event handler function can examine the argument it receives to find out
1722 interesting information about the event and the test program's state.
1723
1724 Here's an example:
1725
1726 ```c++
1727 class MinimalistPrinter : public testing::EmptyTestEventListener {
1728 // Called before a test starts.
1729 void OnTestStart(const testing::TestInfo& test_info) override {
1730 printf("*** Test %s.%s starting.\n",
1731 test_info.test_suite_name(), test_info.name());
1732 }
1733
1734 // Called after a failed assertion or a SUCCESS().
1735 void OnTestPartResult(const testing::TestPartResult& test_part_result) override {
1736 printf("%s in %s:%d\n%s\n",
1737 test_part_result.failed() ? "*** Failure" : "Success",
1738 test_part_result.file_name(),
1739 test_part_result.line_number(),
1740 test_part_result.summary());
1741 }
1742
1743 // Called after a test ends.
1744 void OnTestEnd(const testing::TestInfo& test_info) override {
1745 printf("*** Test %s.%s ending.\n",
1746 test_info.test_suite_name(), test_info.name());
1747 }
1748 };
1749 ```
1750
1751 ### Using Event Listeners
1752
1753 To use the event listener you have defined, add an instance of it to the
1754 GoogleTest event listener list (represented by class
1755 [`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s"
1756 at the end of the name) in your `main()` function, before calling
1757 `RUN_ALL_TESTS()`:
1758
1759 ```c++
1760 int main(int argc, char** argv) {
1761 testing::InitGoogleTest(&argc, argv);
1762 // Gets hold of the event listener list.
1763 testing::TestEventListeners& listeners =
1764 testing::UnitTest::GetInstance()->listeners();
1765 // Adds a listener to the end. GoogleTest takes the ownership.
1766 listeners.Append(new MinimalistPrinter);
1767 return RUN_ALL_TESTS();
1768 }
1769 ```
1770
1771 There's only one problem: the default test result printer is still in effect, so
1772 its output will mingle with the output from your minimalist printer. To suppress
1773 the default printer, just release it from the event listener list and delete it.
1774 You can do so by adding one line:
1775
1776 ```c++
1777 ...
1778 delete listeners.Release(listeners.default_result_printer());
1779 listeners.Append(new MinimalistPrinter);
1780 return RUN_ALL_TESTS();
1781 ```
1782
1783 Now, sit back and enjoy a completely different output from your tests. For more
1784 details, see [sample9_unittest.cc].
1785
1786 [sample9_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc "Event listener example"
1787
1788 You may append more than one listener to the list. When an `On*Start()` or
1789 `OnTestPartResult()` event is fired, the listeners will receive it in the order
1790 they appear in the list (since new listeners are added to the end of the list,
1791 the default text printer and the default XML generator will receive the event
1792 first). An `On*End()` event will be received by the listeners in the *reverse*
1793 order. This allows output by listeners added later to be framed by output from
1794 listeners added earlier.
1795
1796 ### Generating Failures in Listeners
1797
1798 You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, `FAIL()`, etc)
1799 when processing an event. There are some restrictions:
1800
1801 1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will
1802 cause `OnTestPartResult()` to be called recursively).
1803 2. A listener that handles `OnTestPartResult()` is not allowed to generate any
1804 failure.
1805
1806 When you add listeners to the listener list, you should put listeners that
1807 handle `OnTestPartResult()` *before* listeners that can generate failures. This
1808 ensures that failures generated by the latter are attributed to the right test
1809 by the former.
1810
1811 See [sample10_unittest.cc] for an example of a failure-raising listener.
1812
1813 [sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example"
1814
1815 ## Running Test Programs: Advanced Options
1816
1817 GoogleTest test programs are ordinary executables. Once built, you can run them
1818 directly and affect their behavior via the following environment variables
1819 and/or command line flags. For the flags to work, your programs must call
1820 `::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
1821
1822 To see a list of supported flags and their usage, please run your test program
1823 with the `--help` flag.
1824
1825 If an option is specified both by an environment variable and by a flag, the
1826 latter takes precedence.
1827
1828 ### Selecting Tests
1829
1830 #### Listing Test Names
1831
1832 Sometimes it is necessary to list the available tests in a program before
1833 running them so that a filter may be applied if needed. Including the flag
1834 `--gtest_list_tests` overrides all other flags and lists tests in the following
1835 format:
1836
1837 ```none
1838 TestSuite1.
1839 TestName1
1840 TestName2
1841 TestSuite2.
1842 TestName
1843 ```
1844
1845 None of the tests listed are actually run if the flag is provided. There is no
1846 corresponding environment variable for this flag.
1847
1848 #### Running a Subset of the Tests
1849
1850 By default, a GoogleTest program runs all tests the user has defined. Sometimes,
1851 you want to run only a subset of the tests (e.g. for debugging or quickly
1852 verifying a change). If you set the `GTEST_FILTER` environment variable or the
1853 `--gtest_filter` flag to a filter string, GoogleTest will only run the tests
1854 whose full names (in the form of `TestSuiteName.TestName`) match the filter.
1855
1856 The format of a filter is a '`:`'-separated list of wildcard patterns (called
1857 the *positive patterns*) optionally followed by a '`-`' and another
1858 '`:`'-separated pattern list (called the *negative patterns*). A test matches
1859 the filter if and only if it matches any of the positive patterns but does not
1860 match any of the negative patterns.
1861
1862 A pattern may contain `'*'` (matches any string) or `'?'` (matches any single
1863 character). For convenience, the filter `'*-NegativePatterns'` can be also
1864 written as `'-NegativePatterns'`.
1865
1866 For example:
1867
1868 * `./foo_test` Has no flag, and thus runs all its tests.
1869 * `./foo_test --gtest_filter=*` Also runs everything, due to the single
1870 match-everything `*` value.
1871 * `./foo_test --gtest_filter=FooTest.*` Runs everything in test suite
1872 `FooTest` .
1873 * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full
1874 name contains either `"Null"` or `"Constructor"` .
1875 * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests.
1876 * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test
1877 suite `FooTest` except `FooTest.Bar`.
1878 * `./foo_test --gtest_filter=FooTest.*:BarTest.*-FooTest.Bar:BarTest.Foo` Runs
1879 everything in test suite `FooTest` except `FooTest.Bar` and everything in
1880 test suite `BarTest` except `BarTest.Foo`.
1881
1882 #### Stop test execution upon first failure
1883
1884 By default, a GoogleTest program runs all tests the user has defined. In some
1885 cases (e.g. iterative test development & execution) it may be desirable stop
1886 test execution upon first failure (trading improved latency for completeness).
1887 If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set,
1888 the test runner will stop execution as soon as the first test failure is found.
1889
1890 #### Temporarily Disabling Tests
1891
1892 If you have a broken test that you cannot fix right away, you can add the
1893 `DISABLED_` prefix to its name. This will exclude it from execution. This is
1894 better than commenting out the code or using `#if 0`, as disabled tests are
1895 still compiled (and thus won't rot).
1896
1897 If you need to disable all tests in a test suite, you can either add `DISABLED_`
1898 to the front of the name of each test, or alternatively add it to the front of
1899 the test suite name.
1900
1901 For example, the following tests won't be run by GoogleTest, even though they
1902 will still be compiled:
1903
1904 ```c++
1905 // Tests that Foo does Abc.
1906 TEST(FooTest, DISABLED_DoesAbc) { ... }
1907
1908 class DISABLED_BarTest : public testing::Test { ... };
1909
1910 // Tests that Bar does Xyz.
1911 TEST_F(DISABLED_BarTest, DoesXyz) { ... }
1912 ```
1913
1914 {: .callout .note}
1915 NOTE: This feature should only be used for temporary pain-relief. You still have
1916 to fix the disabled tests at a later date. As a reminder, GoogleTest will print
1917 a banner warning you if a test program contains any disabled tests.
1918
1919 {: .callout .tip}
1920 TIP: You can easily count the number of disabled tests you have using
1921 `grep`. This number can be used as a metric for
1922 improving your test quality.
1923
1924 #### Temporarily Enabling Disabled Tests
1925
1926 To include disabled tests in test execution, just invoke the test program with
1927 the `--gtest_also_run_disabled_tests` flag or set the
1928 `GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other than `0`.
1929 You can combine this with the `--gtest_filter` flag to further select which
1930 disabled tests to run.
1931
1932 ### Enforcing Having At Least One Test Case
1933
1934 A not uncommon programmer mistake is to write a test program that has no test
1935 case linked in. This can happen, for example, when you put test case definitions
1936 in a library and the library is not marked as "always link".
1937
1938 To catch such mistakes, run the test program with the
1939 `--gtest_fail_if_no_test_linked` flag or set the `GTEST_FAIL_IF_NO_TEST_LINKED`
1940 environment variable to a value other than `0`. Now the program will fail if no
1941 test case is linked in.
1942
1943 Note that *any* test case linked in makes the program valid for the purpose of
1944 this check. In particular, even a disabled test case suffices.
1945
1946 ### Repeating the Tests
1947
1948 Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it
1949 will fail only 1% of the time, making it rather hard to reproduce the bug under
1950 a debugger. This can be a major source of frustration.
1951
1952 The `--gtest_repeat` flag allows you to repeat all (or selected) test methods in
1953 a program many times. Hopefully, a flaky test will eventually fail and give you
1954 a chance to debug. Here's how to use it:
1955
1956 ```none
1957 $ foo_test --gtest_repeat=1000
1958 Repeat foo_test 1000 times and don't stop at failures.
1959
1960 $ foo_test --gtest_repeat=-1
1961 A negative count means repeating forever.
1962
1963 $ foo_test --gtest_repeat=1000 --gtest_break_on_failure
1964 Repeat foo_test 1000 times, stopping at the first failure. This
1965 is especially useful when running under a debugger: when the test
1966 fails, it will drop into the debugger and you can then inspect
1967 variables and stacks.
1968
1969 $ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.*
1970 Repeat the tests whose name matches the filter 1000 times.
1971 ```
1972
1973 If your test program contains
1974 [global set-up/tear-down](#global-set-up-and-tear-down) code, it will be
1975 repeated in each iteration as well, as the flakiness may be in it. To avoid
1976 repeating global set-up/tear-down, specify
1977 `--gtest_recreate_environments_when_repeating=false`{.nowrap}.
1978
1979 You can also specify the repeat count by setting the `GTEST_REPEAT` environment
1980 variable.
1981
1982 ### Shuffling the Tests
1983
1984 You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`
1985 environment variable to `1`) to run the tests in a program in a random order.
1986 This helps to reveal bad dependencies between tests.
1987
1988 By default, GoogleTest uses a random seed calculated from the current time.
1989 Therefore you'll get a different order every time. The console output includes
1990 the random seed value, such that you can reproduce an order-related test failure
1991 later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED`
1992 flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an
1993 integer in the range [0, 99999]. The seed value 0 is special: it tells
1994 GoogleTest to do the default behavior of calculating the seed from the current
1995 time.
1996
1997 If you combine this with `--gtest_repeat=N`, GoogleTest will pick a different
1998 random seed and re-shuffle the tests in each iteration.
1999
2000 ### Distributing Test Functions to Multiple Machines
2001
2002 If you have more than one machine you can use to run a test program, you might
2003 want to run the test functions in parallel and get the result faster. We call
2004 this technique *sharding*, where each machine is called a *shard*.
2005
2006 GoogleTest is compatible with test sharding. To take advantage of this feature,
2007 your test runner (not part of GoogleTest) needs to do the following:
2008
2009 1. Allocate a number of machines (shards) to run the tests.
2010 1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total
2011 number of shards. It must be the same for all shards.
2012 1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index
2013 of the shard. Different shards must be assigned different indices, which
2014 must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`.
2015 1. Run the same test program on all shards. When GoogleTest sees the above two
2016 environment variables, it will select a subset of the test functions to run.
2017 Across all shards, each test function in the program will be run exactly
2018 once.
2019 1. Wait for all shards to finish, then collect and report the results.
2020
2021 Your project may have tests that were written without GoogleTest and thus don't
2022 understand this protocol. In order for your test runner to figure out which test
2023 supports sharding, it can set the environment variable `GTEST_SHARD_STATUS_FILE`
2024 to a non-existent file path. If a test program supports sharding, it will create
2025 this file to acknowledge that fact; otherwise it will not create it. The actual
2026 contents of the file are not important at this time, although we may put some
2027 useful information in it in the future.
2028
2029 Here's an example to make it clear. Suppose you have a test program `foo_test`
2030 that contains the following 5 test functions:
2031
2032 ```
2033 TEST(A, V)
2034 TEST(A, W)
2035 TEST(B, X)
2036 TEST(B, Y)
2037 TEST(B, Z)
2038 ```
2039
2040 Suppose you have 3 machines at your disposal. To run the test functions in
2041 parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and set
2042 `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. Then you would
2043 run the same `foo_test` on each machine.
2044
2045 GoogleTest reserves the right to change how the work is distributed across the
2046 shards, but here's one possible scenario:
2047
2048 * Machine #0 runs `A.V` and `B.X`.
2049 * Machine #1 runs `A.W` and `B.Y`.
2050 * Machine #2 runs `B.Z`.
2051
2052 ### Controlling Test Output
2053
2054 #### Colored Terminal Output
2055
2056 GoogleTest can use colors in its terminal output to make it easier to spot the
2057 important information:
2058
2059 <pre>...
2060 <font color="green">[----------]</font> 1 test from FooTest
2061 <font color="green">[ RUN ]</font> FooTest.DoesAbc
2062 <font color="green">[ OK ]</font> FooTest.DoesAbc
2063 <font color="green">[----------]</font> 2 tests from BarTest
2064 <font color="green">[ RUN ]</font> BarTest.HasXyzProperty
2065 <font color="green">[ OK ]</font> BarTest.HasXyzProperty
2066 <font color="green">[ RUN ]</font> BarTest.ReturnsTrueOnSuccess
2067 ... some error messages ...
2068 <font color="red">[ FAILED ]</font> BarTest.ReturnsTrueOnSuccess
2069 ...
2070 <font color="green">[==========]</font> 30 tests from 14 test suites ran.
2071 <font color="green">[ PASSED ]</font> 28 tests.
2072 <font color="red">[ FAILED ]</font> 2 tests, listed below:
2073 <font color="red">[ FAILED ]</font> BarTest.ReturnsTrueOnSuccess
2074 <font color="red">[ FAILED ]</font> AnotherTest.DoesXyz
2075
2076 2 FAILED TESTS
2077 </pre>
2078
2079 You can set the `GTEST_COLOR` environment variable or the `--gtest_color`
2080 command line flag to `yes`, `no`, or `auto` (the default) to enable colors,
2081 disable colors, or let GoogleTest decide. When the value is `auto`, GoogleTest
2082 will use colors if and only if the output goes to a terminal and (on non-Windows
2083 platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`.
2084
2085 #### Suppressing test passes
2086
2087 By default, GoogleTest prints 1 line of output for each test, indicating if it
2088 passed or failed. To show only test failures, run the test program with
2089 `--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`.
2090
2091 #### Suppressing the Elapsed Time
2092
2093 By default, GoogleTest prints the time it takes to run each test. To disable
2094 that, run the test program with the `--gtest_print_time=0` command line flag, or
2095 set the GTEST_PRINT_TIME environment variable to `0`.
2096
2097 #### Suppressing UTF-8 Text Output
2098
2099 In case of assertion failures, GoogleTest prints expected and actual values of
2100 type `string` both as hex-encoded strings as well as in readable UTF-8 text if
2101 they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8
2102 text because, for example, you don't have an UTF-8 compatible output medium, run
2103 the test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8`
2104 environment variable to `0`.
2105
2106 #### Generating an XML Report
2107
2108 GoogleTest can emit a detailed XML report to a file in addition to its normal
2109 textual output. The report contains the duration of each test, and thus can help
2110 you identify slow tests.
2111
2112 To generate the XML report, set the `GTEST_OUTPUT` environment variable or the
2113 `--gtest_output` flag to the string `"xml:path_to_output_file"`, which will
2114 create the file at the given location. You can also just use the string `"xml"`,
2115 in which case the output can be found in the `test_detail.xml` file in the
2116 current directory.
2117
2118 If you specify a directory (for example, `"xml:output/directory/"` on Linux or
2119 `"xml:output\directory\"` on Windows), GoogleTest will create the XML file in
2120 that directory, named after the test executable (e.g. `foo_test.xml` for test
2121 program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left
2122 over from a previous run), GoogleTest will pick a different name (e.g.
2123 `foo_test_1.xml`) to avoid overwriting it.
2124
2125 The report is based on the `junitreport` Ant task. Since that format was
2126 originally intended for Java, a little interpretation is required to make it
2127 apply to GoogleTest tests, as shown here:
2128
2129 ```xml
2130 <testsuites name="AllTests" ...>
2131 <testsuite name="test_case_name" ...>
2132 <testcase name="test_name" ...>
2133 <failure message="..."/>
2134 <failure message="..."/>
2135 <failure message="..."/>
2136 </testcase>
2137 </testsuite>
2138 </testsuites>
2139 ```
2140
2141 * The root `<testsuites>` element corresponds to the entire test program.
2142 * `<testsuite>` elements correspond to GoogleTest test suites.
2143 * `<testcase>` elements correspond to GoogleTest test functions.
2144
2145 For instance, the following program
2146
2147 ```c++
2148 TEST(MathTest, Addition) { ... }
2149 TEST(MathTest, Subtraction) { ... }
2150 TEST(LogicTest, NonContradiction) { ... }
2151 ```
2152
2153 could generate this report:
2154
2155 ```xml
2156 <?xml version="1.0" encoding="UTF-8"?>
2157 <testsuites tests="3" failures="1" errors="0" time="0.035" timestamp="2011-10-31T18:52:42" name="AllTests">
2158 <testsuite name="MathTest" tests="2" failures="1" errors="0" time="0.015">
2159 <testcase name="Addition" file="test.cpp" line="1" status="run" time="0.007" classname="">
2160 <failure message="Value of: add(1, 1)&#x0A; Actual: 3&#x0A;Expected: 2" type="">...</failure>
2161 <failure message="Value of: add(1, -1)&#x0A; Actual: 1&#x0A;Expected: 0" type="">...</failure>
2162 </testcase>
2163 <testcase name="Subtraction" file="test.cpp" line="2" status="run" time="0.005" classname="">
2164 </testcase>
2165 </testsuite>
2166 <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="0.005">
2167 <testcase name="NonContradiction" file="test.cpp" line="3" status="run" time="0.005" classname="">
2168 </testcase>
2169 </testsuite>
2170 </testsuites>
2171 ```
2172
2173 Things to note:
2174
2175 * The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how
2176 many test functions the GoogleTest program or test suite contains, while the
2177 `failures` attribute tells how many of them failed.
2178
2179 * The `time` attribute expresses the duration of the test, test suite, or
2180 entire test program in seconds.
2181
2182 * The `timestamp` attribute records the local date and time of the test
2183 execution.
2184
2185 * The `file` and `line` attributes record the source file location, where the
2186 test was defined.
2187
2188 * Each `<failure>` element corresponds to a single failed GoogleTest
2189 assertion.
2190
2191 #### Generating a JSON Report
2192
2193 GoogleTest can also emit a JSON report as an alternative format to XML. To
2194 generate the JSON report, set the `GTEST_OUTPUT` environment variable or the
2195 `--gtest_output` flag to the string `"json:path_to_output_file"`, which will
2196 create the file at the given location. You can also just use the string
2197 `"json"`, in which case the output can be found in the `test_detail.json` file
2198 in the current directory.
2199
2200 The report format conforms to the following JSON Schema:
2201
2202 ```json
2203 {
2204 "$schema": "https://json-schema.org/schema#",
2205 "type": "object",
2206 "definitions": {
2207 "TestCase": {
2208 "type": "object",
2209 "properties": {
2210 "name": { "type": "string" },
2211 "tests": { "type": "integer" },
2212 "failures": { "type": "integer" },
2213 "disabled": { "type": "integer" },
2214 "time": { "type": "string" },
2215 "testsuite": {
2216 "type": "array",
2217 "items": {
2218 "$ref": "#/definitions/TestInfo"
2219 }
2220 }
2221 }
2222 },
2223 "TestInfo": {
2224 "type": "object",
2225 "properties": {
2226 "name": { "type": "string" },
2227 "file": { "type": "string" },
2228 "line": { "type": "integer" },
2229 "status": {
2230 "type": "string",
2231 "enum": ["RUN", "NOTRUN"]
2232 },
2233 "time": { "type": "string" },
2234 "classname": { "type": "string" },
2235 "failures": {
2236 "type": "array",
2237 "items": {
2238 "$ref": "#/definitions/Failure"
2239 }
2240 }
2241 }
2242 },
2243 "Failure": {
2244 "type": "object",
2245 "properties": {
2246 "failures": { "type": "string" },
2247 "type": { "type": "string" }
2248 }
2249 }
2250 },
2251 "properties": {
2252 "tests": { "type": "integer" },
2253 "failures": { "type": "integer" },
2254 "disabled": { "type": "integer" },
2255 "errors": { "type": "integer" },
2256 "timestamp": {
2257 "type": "string",
2258 "format": "date-time"
2259 },
2260 "time": { "type": "string" },
2261 "name": { "type": "string" },
2262 "testsuites": {
2263 "type": "array",
2264 "items": {
2265 "$ref": "#/definitions/TestCase"
2266 }
2267 }
2268 }
2269 }
2270 ```
2271
2272 The report uses the format that conforms to the following Proto3 using the
2273 [JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json):
2274
2275 ```proto
2276 syntax = "proto3";
2277
2278 package googletest;
2279
2280 import "google/protobuf/timestamp.proto";
2281 import "google/protobuf/duration.proto";
2282
2283 message UnitTest {
2284 int32 tests = 1;
2285 int32 failures = 2;
2286 int32 disabled = 3;
2287 int32 errors = 4;
2288 google.protobuf.Timestamp timestamp = 5;
2289 google.protobuf.Duration time = 6;
2290 string name = 7;
2291 repeated TestCase testsuites = 8;
2292 }
2293
2294 message TestCase {
2295 string name = 1;
2296 int32 tests = 2;
2297 int32 failures = 3;
2298 int32 disabled = 4;
2299 int32 errors = 5;
2300 google.protobuf.Duration time = 6;
2301 repeated TestInfo testsuite = 7;
2302 }
2303
2304 message TestInfo {
2305 string name = 1;
2306 string file = 6;
2307 int32 line = 7;
2308 enum Status {
2309 RUN = 0;
2310 NOTRUN = 1;
2311 }
2312 Status status = 2;
2313 google.protobuf.Duration time = 3;
2314 string classname = 4;
2315 message Failure {
2316 string failures = 1;
2317 string type = 2;
2318 }
2319 repeated Failure failures = 5;
2320 }
2321 ```
2322
2323 For instance, the following program
2324
2325 ```c++
2326 TEST(MathTest, Addition) { ... }
2327 TEST(MathTest, Subtraction) { ... }
2328 TEST(LogicTest, NonContradiction) { ... }
2329 ```
2330
2331 could generate this report:
2332
2333 ```json
2334 {
2335 "tests": 3,
2336 "failures": 1,
2337 "errors": 0,
2338 "time": "0.035s",
2339 "timestamp": "2011-10-31T18:52:42Z",
2340 "name": "AllTests",
2341 "testsuites": [
2342 {
2343 "name": "MathTest",
2344 "tests": 2,
2345 "failures": 1,
2346 "errors": 0,
2347 "time": "0.015s",
2348 "testsuite": [
2349 {
2350 "name": "Addition",
2351 "file": "test.cpp",
2352 "line": 1,
2353 "status": "RUN",
2354 "time": "0.007s",
2355 "classname": "",
2356 "failures": [
2357 {
2358 "message": "Value of: add(1, 1)\n Actual: 3\nExpected: 2",
2359 "type": ""
2360 },
2361 {
2362 "message": "Value of: add(1, -1)\n Actual: 1\nExpected: 0",
2363 "type": ""
2364 }
2365 ]
2366 },
2367 {
2368 "name": "Subtraction",
2369 "file": "test.cpp",
2370 "line": 2,
2371 "status": "RUN",
2372 "time": "0.005s",
2373 "classname": ""
2374 }
2375 ]
2376 },
2377 {
2378 "name": "LogicTest",
2379 "tests": 1,
2380 "failures": 0,
2381 "errors": 0,
2382 "time": "0.005s",
2383 "testsuite": [
2384 {
2385 "name": "NonContradiction",
2386 "file": "test.cpp",
2387 "line": 3,
2388 "status": "RUN",
2389 "time": "0.005s",
2390 "classname": ""
2391 }
2392 ]
2393 }
2394 ]
2395 }
2396 ```
2397
2398 {: .callout .important}
2399 IMPORTANT: The exact format of the JSON document is subject to change.
2400
2401 ### Controlling How Failures Are Reported
2402
2403 #### Detecting Test Premature Exit
2404
2405 Google Test implements the *premature-exit-file* protocol for test runners to
2406 catch any kind of unexpected exits of test programs. Upon start, Google Test
2407 creates the file which will be automatically deleted after all work has been
2408 finished. Then, the test runner can check if this file exists. In case the file
2409 remains undeleted, the inspected test has exited prematurely.
2410
2411 This feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment
2412 variable has been set.
2413
2414 #### Turning Assertion Failures into Break-Points
2415
2416 When running test programs under a debugger, it's very convenient if the
2417 debugger can catch an assertion failure and automatically drop into interactive
2418 mode. GoogleTest's *break-on-failure* mode supports this behavior.
2419
2420 To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value
2421 other than `0`. Alternatively, you can use the `--gtest_break_on_failure`
2422 command line flag.
2423
2424 #### Disabling Catching Test-Thrown Exceptions
2425
2426 GoogleTest can be used either with or without exceptions enabled. If a test
2427 throws a C++ exception or (on Windows) a structured exception (SEH), by default
2428 GoogleTest catches it, reports it as a test failure, and continues with the next
2429 test method. This maximizes the coverage of a test run. Also, on Windows an
2430 uncaught exception will cause a pop-up window, so catching the exceptions allows
2431 you to run the tests automatically.
2432
2433 When debugging the test failures, however, you may instead want the exceptions
2434 to be handled by the debugger, such that you can examine the call stack when an
2435 exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS`
2436 environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when
2437 running the tests.
2438
2439 ### Sanitizer Integration
2440
2441 The
2442 [Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html),
2443 [Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer),
2444 and
2445 [Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual)
2446 all provide weak functions that you can override to trigger explicit failures
2447 when they detect sanitizer errors, such as creating a reference from `nullptr`.
2448 To override these functions, place definitions for them in a source file that
2449 you compile as part of your main binary:
2450
2451 ```
2452 extern "C" {
2453 void __ubsan_on_report() {
2454 FAIL() << "Encountered an undefined behavior sanitizer error";
2455 }
2456 void __asan_on_error() {
2457 FAIL() << "Encountered an address sanitizer error";
2458 }
2459 void __tsan_on_report() {
2460 FAIL() << "Encountered a thread sanitizer error";
2461 }
2462 } // extern "C"
2463 ```
2464
2465 After compiling your project with one of the sanitizers enabled, if a particular
2466 test triggers a sanitizer error, GoogleTest will report that it failed.