128f6c2f2SEnji Cooper# Advanced GoogleTest Topics 228f6c2f2SEnji Cooper 328f6c2f2SEnji Cooper## Introduction 428f6c2f2SEnji Cooper 528f6c2f2SEnji CooperNow that you have read the [GoogleTest Primer](primer.md) and learned how to 628f6c2f2SEnji Cooperwrite tests using GoogleTest, it's time to learn some new tricks. This document 728f6c2f2SEnji Cooperwill show you more assertions as well as how to construct complex failure 828f6c2f2SEnji Coopermessages, propagate fatal failures, reuse and speed up your test fixtures, and 928f6c2f2SEnji Cooperuse various flags with your tests. 1028f6c2f2SEnji Cooper 1128f6c2f2SEnji Cooper## More Assertions 1228f6c2f2SEnji Cooper 1328f6c2f2SEnji CooperThis section covers some less frequently used, but still significant, 1428f6c2f2SEnji Cooperassertions. 1528f6c2f2SEnji Cooper 1628f6c2f2SEnji Cooper### Explicit Success and Failure 1728f6c2f2SEnji Cooper 1828f6c2f2SEnji CooperSee [Explicit Success and Failure](reference/assertions.md#success-failure) in 1928f6c2f2SEnji Cooperthe Assertions Reference. 2028f6c2f2SEnji Cooper 2128f6c2f2SEnji Cooper### Exception Assertions 2228f6c2f2SEnji Cooper 2328f6c2f2SEnji CooperSee [Exception Assertions](reference/assertions.md#exceptions) in the Assertions 2428f6c2f2SEnji CooperReference. 2528f6c2f2SEnji Cooper 2628f6c2f2SEnji Cooper### Predicate Assertions for Better Error Messages 2728f6c2f2SEnji Cooper 2828f6c2f2SEnji CooperEven though GoogleTest has a rich set of assertions, they can never be complete, 2928f6c2f2SEnji Cooperas it's impossible (nor a good idea) to anticipate all scenarios a user might 3028f6c2f2SEnji Cooperrun into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a 3128f6c2f2SEnji Coopercomplex expression, for lack of a better macro. This has the problem of not 3228f6c2f2SEnji Coopershowing you the values of the parts of the expression, making it hard to 3328f6c2f2SEnji Cooperunderstand what went wrong. As a workaround, some users choose to construct the 3428f6c2f2SEnji Cooperfailure message by themselves, streaming it into `EXPECT_TRUE()`. However, this 3528f6c2f2SEnji Cooperis awkward especially when the expression has side-effects or is expensive to 3628f6c2f2SEnji Cooperevaluate. 3728f6c2f2SEnji Cooper 3828f6c2f2SEnji CooperGoogleTest gives you three different options to solve this problem: 3928f6c2f2SEnji Cooper 4028f6c2f2SEnji Cooper#### Using an Existing Boolean Function 4128f6c2f2SEnji Cooper 4228f6c2f2SEnji CooperIf you already have a function or functor that returns `bool` (or a type that 4328f6c2f2SEnji Coopercan be implicitly converted to `bool`), you can use it in a *predicate 4428f6c2f2SEnji Cooperassertion* to get the function arguments printed for free. See 4528f6c2f2SEnji Cooper[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions 4628f6c2f2SEnji CooperReference for details. 4728f6c2f2SEnji Cooper 4828f6c2f2SEnji Cooper#### Using a Function That Returns an AssertionResult 4928f6c2f2SEnji Cooper 5028f6c2f2SEnji CooperWhile `EXPECT_PRED*()` and friends are handy for a quick job, the syntax is not 5128f6c2f2SEnji Coopersatisfactory: you have to use different macros for different arities, and it 5228f6c2f2SEnji Cooperfeels more like Lisp than C++. The `::testing::AssertionResult` class solves 5328f6c2f2SEnji Cooperthis problem. 5428f6c2f2SEnji Cooper 5528f6c2f2SEnji CooperAn `AssertionResult` object represents the result of an assertion (whether it's 5628f6c2f2SEnji Coopera success or a failure, and an associated message). You can create an 5728f6c2f2SEnji Cooper`AssertionResult` using one of these factory functions: 5828f6c2f2SEnji Cooper 5928f6c2f2SEnji Cooper```c++ 6028f6c2f2SEnji Coopernamespace testing { 6128f6c2f2SEnji Cooper 6228f6c2f2SEnji Cooper// Returns an AssertionResult object to indicate that an assertion has 6328f6c2f2SEnji Cooper// succeeded. 6428f6c2f2SEnji CooperAssertionResult AssertionSuccess(); 6528f6c2f2SEnji Cooper 6628f6c2f2SEnji Cooper// Returns an AssertionResult object to indicate that an assertion has 6728f6c2f2SEnji Cooper// failed. 6828f6c2f2SEnji CooperAssertionResult AssertionFailure(); 6928f6c2f2SEnji Cooper 7028f6c2f2SEnji Cooper} 7128f6c2f2SEnji Cooper``` 7228f6c2f2SEnji Cooper 7328f6c2f2SEnji CooperYou can then use the `<<` operator to stream messages to the `AssertionResult` 7428f6c2f2SEnji Cooperobject. 7528f6c2f2SEnji Cooper 7628f6c2f2SEnji CooperTo provide more readable messages in Boolean assertions (e.g. `EXPECT_TRUE()`), 7728f6c2f2SEnji Cooperwrite a predicate function that returns `AssertionResult` instead of `bool`. For 7828f6c2f2SEnji Cooperexample, if you define `IsEven()` as: 7928f6c2f2SEnji Cooper 8028f6c2f2SEnji Cooper```c++ 8128f6c2f2SEnji Coopertesting::AssertionResult IsEven(int n) { 8228f6c2f2SEnji Cooper if ((n % 2) == 0) 8328f6c2f2SEnji Cooper return testing::AssertionSuccess(); 8428f6c2f2SEnji Cooper else 8528f6c2f2SEnji Cooper return testing::AssertionFailure() << n << " is odd"; 8628f6c2f2SEnji Cooper} 8728f6c2f2SEnji Cooper``` 8828f6c2f2SEnji Cooper 8928f6c2f2SEnji Cooperinstead of: 9028f6c2f2SEnji Cooper 9128f6c2f2SEnji Cooper```c++ 9228f6c2f2SEnji Cooperbool IsEven(int n) { 9328f6c2f2SEnji Cooper return (n % 2) == 0; 9428f6c2f2SEnji Cooper} 9528f6c2f2SEnji Cooper``` 9628f6c2f2SEnji Cooper 9728f6c2f2SEnji Cooperthe failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: 9828f6c2f2SEnji Cooper 9928f6c2f2SEnji Cooper```none 10028f6c2f2SEnji CooperValue of: IsEven(Fib(4)) 10128f6c2f2SEnji Cooper Actual: false (3 is odd) 10228f6c2f2SEnji CooperExpected: true 10328f6c2f2SEnji Cooper``` 10428f6c2f2SEnji Cooper 10528f6c2f2SEnji Cooperinstead of a more opaque 10628f6c2f2SEnji Cooper 10728f6c2f2SEnji Cooper```none 10828f6c2f2SEnji CooperValue of: IsEven(Fib(4)) 10928f6c2f2SEnji Cooper Actual: false 11028f6c2f2SEnji CooperExpected: true 11128f6c2f2SEnji Cooper``` 11228f6c2f2SEnji Cooper 11328f6c2f2SEnji CooperIf you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` as well 11428f6c2f2SEnji Cooper(one third of Boolean assertions in the Google code base are negative ones), and 11528f6c2f2SEnji Cooperare fine with making the predicate slower in the success case, you can supply a 11628f6c2f2SEnji Coopersuccess message: 11728f6c2f2SEnji Cooper 11828f6c2f2SEnji Cooper```c++ 11928f6c2f2SEnji Coopertesting::AssertionResult IsEven(int n) { 12028f6c2f2SEnji Cooper if ((n % 2) == 0) 12128f6c2f2SEnji Cooper return testing::AssertionSuccess() << n << " is even"; 12228f6c2f2SEnji Cooper else 12328f6c2f2SEnji Cooper return testing::AssertionFailure() << n << " is odd"; 12428f6c2f2SEnji Cooper} 12528f6c2f2SEnji Cooper``` 12628f6c2f2SEnji Cooper 12728f6c2f2SEnji CooperThen the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print 12828f6c2f2SEnji Cooper 12928f6c2f2SEnji Cooper```none 13028f6c2f2SEnji Cooper Value of: IsEven(Fib(6)) 13128f6c2f2SEnji Cooper Actual: true (8 is even) 13228f6c2f2SEnji Cooper Expected: false 13328f6c2f2SEnji Cooper``` 13428f6c2f2SEnji Cooper 13528f6c2f2SEnji Cooper#### Using a Predicate-Formatter 13628f6c2f2SEnji Cooper 13728f6c2f2SEnji CooperIf you find the default message generated by 13828f6c2f2SEnji Cooper[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) and 13928f6c2f2SEnji Cooper[`EXPECT_TRUE`](reference/assertions.md#EXPECT_TRUE) unsatisfactory, or some 14028f6c2f2SEnji Cooperarguments to your predicate do not support streaming to `ostream`, you can 14128f6c2f2SEnji Cooperinstead use *predicate-formatter assertions* to *fully* customize how the 14228f6c2f2SEnji Coopermessage is formatted. See 14328f6c2f2SEnji Cooper[`EXPECT_PRED_FORMAT*`](reference/assertions.md#EXPECT_PRED_FORMAT) in the 14428f6c2f2SEnji CooperAssertions Reference for details. 14528f6c2f2SEnji Cooper 14628f6c2f2SEnji Cooper### Floating-Point Comparison 14728f6c2f2SEnji Cooper 14828f6c2f2SEnji CooperSee [Floating-Point Comparison](reference/assertions.md#floating-point) in the 14928f6c2f2SEnji CooperAssertions Reference. 15028f6c2f2SEnji Cooper 15128f6c2f2SEnji Cooper#### Floating-Point Predicate-Format Functions 15228f6c2f2SEnji Cooper 15328f6c2f2SEnji CooperSome floating-point operations are useful, but not that often used. In order to 15428f6c2f2SEnji Cooperavoid an explosion of new macros, we provide them as predicate-format functions 15528f6c2f2SEnji Cooperthat can be used in the predicate assertion macro 15628f6c2f2SEnji Cooper[`EXPECT_PRED_FORMAT2`](reference/assertions.md#EXPECT_PRED_FORMAT), for 15728f6c2f2SEnji Cooperexample: 15828f6c2f2SEnji Cooper 15928f6c2f2SEnji Cooper```c++ 16028f6c2f2SEnji Cooperusing ::testing::FloatLE; 16128f6c2f2SEnji Cooperusing ::testing::DoubleLE; 16228f6c2f2SEnji Cooper... 16328f6c2f2SEnji CooperEXPECT_PRED_FORMAT2(FloatLE, val1, val2); 16428f6c2f2SEnji CooperEXPECT_PRED_FORMAT2(DoubleLE, val1, val2); 16528f6c2f2SEnji Cooper``` 16628f6c2f2SEnji Cooper 16728f6c2f2SEnji CooperThe above code verifies that `val1` is less than, or approximately equal to, 16828f6c2f2SEnji Cooper`val2`. 16928f6c2f2SEnji Cooper 17028f6c2f2SEnji Cooper### Asserting Using gMock Matchers 17128f6c2f2SEnji Cooper 17228f6c2f2SEnji CooperSee [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions 17328f6c2f2SEnji CooperReference. 17428f6c2f2SEnji Cooper 17528f6c2f2SEnji Cooper### More String Assertions 17628f6c2f2SEnji Cooper 17728f6c2f2SEnji Cooper(Please read the [previous](#asserting-using-gmock-matchers) section first if 17828f6c2f2SEnji Cooperyou haven't.) 17928f6c2f2SEnji Cooper 18028f6c2f2SEnji CooperYou can use the gMock [string matchers](reference/matchers.md#string-matchers) 18128f6c2f2SEnji Cooperwith [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) to do more string 18228f6c2f2SEnji Coopercomparison tricks (sub-string, prefix, suffix, regular expression, and etc). For 18328f6c2f2SEnji Cooperexample, 18428f6c2f2SEnji Cooper 18528f6c2f2SEnji Cooper```c++ 18628f6c2f2SEnji Cooperusing ::testing::HasSubstr; 18728f6c2f2SEnji Cooperusing ::testing::MatchesRegex; 18828f6c2f2SEnji Cooper... 18928f6c2f2SEnji Cooper ASSERT_THAT(foo_string, HasSubstr("needle")); 19028f6c2f2SEnji Cooper EXPECT_THAT(bar_string, MatchesRegex("\\w*\\d+")); 19128f6c2f2SEnji Cooper``` 19228f6c2f2SEnji Cooper 19328f6c2f2SEnji Cooper### Windows HRESULT assertions 19428f6c2f2SEnji Cooper 19528f6c2f2SEnji CooperSee [Windows HRESULT Assertions](reference/assertions.md#HRESULT) in the 19628f6c2f2SEnji CooperAssertions Reference. 19728f6c2f2SEnji Cooper 19828f6c2f2SEnji Cooper### Type Assertions 19928f6c2f2SEnji Cooper 20028f6c2f2SEnji CooperYou can call the function 20128f6c2f2SEnji Cooper 20228f6c2f2SEnji Cooper```c++ 20328f6c2f2SEnji Cooper::testing::StaticAssertTypeEq<T1, T2>(); 20428f6c2f2SEnji Cooper``` 20528f6c2f2SEnji Cooper 20628f6c2f2SEnji Cooperto assert that types `T1` and `T2` are the same. The function does nothing if 20728f6c2f2SEnji Cooperthe assertion is satisfied. If the types are different, the function call will 20828f6c2f2SEnji Cooperfail to compile, the compiler error message will say that `T1 and T2 are not the 20928f6c2f2SEnji Coopersame type` and most likely (depending on the compiler) show you the actual 21028f6c2f2SEnji Coopervalues of `T1` and `T2`. This is mainly useful inside template code. 21128f6c2f2SEnji Cooper 21228f6c2f2SEnji Cooper**Caveat**: When used inside a member function of a class template or a function 21328f6c2f2SEnji Coopertemplate, `StaticAssertTypeEq<T1, T2>()` is effective only if the function is 21428f6c2f2SEnji Cooperinstantiated. For example, given: 21528f6c2f2SEnji Cooper 21628f6c2f2SEnji Cooper```c++ 21728f6c2f2SEnji Coopertemplate <typename T> class Foo { 21828f6c2f2SEnji Cooper public: 21928f6c2f2SEnji Cooper void Bar() { testing::StaticAssertTypeEq<int, T>(); } 22028f6c2f2SEnji Cooper}; 22128f6c2f2SEnji Cooper``` 22228f6c2f2SEnji Cooper 22328f6c2f2SEnji Cooperthe code: 22428f6c2f2SEnji Cooper 22528f6c2f2SEnji Cooper```c++ 22628f6c2f2SEnji Coopervoid Test1() { Foo<bool> foo; } 22728f6c2f2SEnji Cooper``` 22828f6c2f2SEnji Cooper 22928f6c2f2SEnji Cooperwill not generate a compiler error, as `Foo<bool>::Bar()` is never actually 23028f6c2f2SEnji Cooperinstantiated. Instead, you need: 23128f6c2f2SEnji Cooper 23228f6c2f2SEnji Cooper```c++ 23328f6c2f2SEnji Coopervoid Test2() { Foo<bool> foo; foo.Bar(); } 23428f6c2f2SEnji Cooper``` 23528f6c2f2SEnji Cooper 23628f6c2f2SEnji Cooperto cause a compiler error. 23728f6c2f2SEnji Cooper 23828f6c2f2SEnji Cooper### Assertion Placement 23928f6c2f2SEnji Cooper 24028f6c2f2SEnji CooperYou can use assertions in any C++ function. In particular, it doesn't have to be 24128f6c2f2SEnji Coopera method of the test fixture class. The one constraint is that assertions that 24228f6c2f2SEnji Coopergenerate a fatal failure (`FAIL*` and `ASSERT_*`) can only be used in 24328f6c2f2SEnji Coopervoid-returning functions. This is a consequence of Google's not using 24428f6c2f2SEnji Cooperexceptions. By placing it in a non-void function you'll get a confusing compile 24528f6c2f2SEnji Coopererror like `"error: void value not ignored as it ought to be"` or `"cannot 24628f6c2f2SEnji Cooperinitialize return object of type 'bool' with an rvalue of type 'void'"` or 24728f6c2f2SEnji Cooper`"error: no viable conversion from 'void' to 'string'"`. 24828f6c2f2SEnji Cooper 24928f6c2f2SEnji CooperIf you need to use fatal assertions in a function that returns non-void, one 25028f6c2f2SEnji Cooperoption is to make the function return the value in an out parameter instead. For 25128f6c2f2SEnji Cooperexample, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You 25228f6c2f2SEnji Cooperneed to make sure that `*result` contains some sensible value even when the 25328f6c2f2SEnji Cooperfunction returns prematurely. As the function now returns `void`, you can use 25428f6c2f2SEnji Cooperany assertion inside of it. 25528f6c2f2SEnji Cooper 25628f6c2f2SEnji CooperIf changing the function's type is not an option, you should just use assertions 25728f6c2f2SEnji Cooperthat generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`. 25828f6c2f2SEnji Cooper 25928f6c2f2SEnji Cooper{: .callout .note} 26028f6c2f2SEnji CooperNOTE: Constructors and destructors are not considered void-returning functions, 26128f6c2f2SEnji Cooperaccording to the C++ language specification, and so you may not use fatal 26228f6c2f2SEnji Cooperassertions in them; you'll get a compilation error if you try. Instead, either 26328f6c2f2SEnji Coopercall `abort` and crash the entire test executable, or put the fatal assertion in 26428f6c2f2SEnji Coopera `SetUp`/`TearDown` function; see 26528f6c2f2SEnji Cooper[constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp) 26628f6c2f2SEnji Cooper 26728f6c2f2SEnji Cooper{: .callout .warning} 26828f6c2f2SEnji CooperWARNING: A fatal assertion in a helper function (private void-returning method) 26928f6c2f2SEnji Coopercalled from a constructor or destructor does not terminate the current test, as 27028f6c2f2SEnji Cooperyour intuition might suggest: it merely returns from the constructor or 27128f6c2f2SEnji Cooperdestructor early, possibly leaving your object in a partially-constructed or 27228f6c2f2SEnji Cooperpartially-destructed state! You almost certainly want to `abort` or use 27328f6c2f2SEnji Cooper`SetUp`/`TearDown` instead. 27428f6c2f2SEnji Cooper 27528f6c2f2SEnji Cooper## Skipping test execution 27628f6c2f2SEnji Cooper 27728f6c2f2SEnji CooperRelated to the assertions `SUCCEED()` and `FAIL()`, you can prevent further test 27828f6c2f2SEnji Cooperexecution at runtime with the `GTEST_SKIP()` macro. This is useful when you need 27928f6c2f2SEnji Cooperto check for preconditions of the system under test during runtime and skip 28028f6c2f2SEnji Coopertests in a meaningful way. 28128f6c2f2SEnji Cooper 28228f6c2f2SEnji Cooper`GTEST_SKIP()` can be used in individual test cases or in the `SetUp()` methods 28328f6c2f2SEnji Cooperof classes derived from either `::testing::Environment` or `::testing::Test`. 28428f6c2f2SEnji CooperFor example: 28528f6c2f2SEnji Cooper 28628f6c2f2SEnji Cooper```c++ 28728f6c2f2SEnji CooperTEST(SkipTest, DoesSkip) { 28828f6c2f2SEnji Cooper GTEST_SKIP() << "Skipping single test"; 28928f6c2f2SEnji Cooper EXPECT_EQ(0, 1); // Won't fail; it won't be executed 29028f6c2f2SEnji Cooper} 29128f6c2f2SEnji Cooper 29228f6c2f2SEnji Cooperclass SkipFixture : public ::testing::Test { 29328f6c2f2SEnji Cooper protected: 29428f6c2f2SEnji Cooper void SetUp() override { 29528f6c2f2SEnji Cooper GTEST_SKIP() << "Skipping all tests for this fixture"; 29628f6c2f2SEnji Cooper } 29728f6c2f2SEnji Cooper}; 29828f6c2f2SEnji Cooper 29928f6c2f2SEnji Cooper// Tests for SkipFixture won't be executed. 30028f6c2f2SEnji CooperTEST_F(SkipFixture, SkipsOneTest) { 30128f6c2f2SEnji Cooper EXPECT_EQ(5, 7); // Won't fail 30228f6c2f2SEnji Cooper} 30328f6c2f2SEnji Cooper``` 30428f6c2f2SEnji Cooper 30528f6c2f2SEnji CooperAs with assertion macros, you can stream a custom message into `GTEST_SKIP()`. 30628f6c2f2SEnji Cooper 30728f6c2f2SEnji Cooper## Teaching GoogleTest How to Print Your Values 30828f6c2f2SEnji Cooper 30928f6c2f2SEnji CooperWhen a test assertion such as `EXPECT_EQ` fails, GoogleTest prints the argument 31028f6c2f2SEnji Coopervalues to help you debug. It does this using a user-extensible value printer. 31128f6c2f2SEnji Cooper 31228f6c2f2SEnji CooperThis printer knows how to print built-in C++ types, native arrays, STL 31328f6c2f2SEnji Coopercontainers, and any type that supports the `<<` operator. For other types, it 31428f6c2f2SEnji Cooperprints the raw bytes in the value and hopes that you the user can figure it out. 31528f6c2f2SEnji Cooper 31628f6c2f2SEnji CooperAs mentioned earlier, the printer is *extensible*. That means you can teach it 31728f6c2f2SEnji Cooperto do a better job at printing your particular type than to dump the bytes. To 31828f6c2f2SEnji Cooperdo that, define an `AbslStringify()` overload as a `friend` function template 31928f6c2f2SEnji Cooperfor your type: 32028f6c2f2SEnji Cooper 32128f6c2f2SEnji Cooper```cpp 32228f6c2f2SEnji Coopernamespace foo { 32328f6c2f2SEnji Cooper 32428f6c2f2SEnji Cooperclass Point { // We want GoogleTest to be able to print instances of this. 32528f6c2f2SEnji Cooper ... 32628f6c2f2SEnji Cooper // Provide a friend overload. 32728f6c2f2SEnji Cooper template <typename Sink> 32828f6c2f2SEnji Cooper friend void AbslStringify(Sink& sink, const Point& point) { 32928f6c2f2SEnji Cooper absl::Format(&sink, "(%d, %d)", point.x, point.y); 33028f6c2f2SEnji Cooper } 33128f6c2f2SEnji Cooper 33228f6c2f2SEnji Cooper int x; 33328f6c2f2SEnji Cooper int y; 33428f6c2f2SEnji Cooper}; 33528f6c2f2SEnji Cooper 33628f6c2f2SEnji Cooper// If you can't declare the function in the class it's important that the 33728f6c2f2SEnji Cooper// AbslStringify overload is defined in the SAME namespace that defines Point. 33828f6c2f2SEnji Cooper// C++'s look-up rules rely on that. 33928f6c2f2SEnji Cooperenum class EnumWithStringify { kMany = 0, kChoices = 1 }; 34028f6c2f2SEnji Cooper 34128f6c2f2SEnji Coopertemplate <typename Sink> 34228f6c2f2SEnji Coopervoid AbslStringify(Sink& sink, EnumWithStringify e) { 34328f6c2f2SEnji Cooper absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices"); 34428f6c2f2SEnji Cooper} 34528f6c2f2SEnji Cooper 34628f6c2f2SEnji Cooper} // namespace foo 34728f6c2f2SEnji Cooper``` 34828f6c2f2SEnji Cooper 34928f6c2f2SEnji Cooper{: .callout .note} 35028f6c2f2SEnji CooperNote: `AbslStringify()` utilizes a generic "sink" buffer to construct its 35128f6c2f2SEnji Cooperstring. For more information about supported operations on `AbslStringify()`'s 35228f6c2f2SEnji Coopersink, see go/abslstringify. 35328f6c2f2SEnji Cooper 35428f6c2f2SEnji Cooper`AbslStringify()` can also use `absl::StrFormat`'s catch-all `%v` type specifier 35528f6c2f2SEnji Cooperwithin its own format strings to perform type deduction. `Point` above could be 35628f6c2f2SEnji Cooperformatted as `"(%v, %v)"` for example, and deduce the `int` values as `%d`. 35728f6c2f2SEnji Cooper 35828f6c2f2SEnji CooperSometimes, `AbslStringify()` might not be an option: your team may wish to print 35928f6c2f2SEnji Coopertypes with extra debugging information for testing purposes only. If so, you can 36028f6c2f2SEnji Cooperinstead define a `PrintTo()` function like this: 36128f6c2f2SEnji Cooper 36228f6c2f2SEnji Cooper```c++ 36328f6c2f2SEnji Cooper#include <ostream> 36428f6c2f2SEnji Cooper 36528f6c2f2SEnji Coopernamespace foo { 36628f6c2f2SEnji Cooper 36728f6c2f2SEnji Cooperclass Point { 36828f6c2f2SEnji Cooper ... 36928f6c2f2SEnji Cooper friend void PrintTo(const Point& point, std::ostream* os) { 37028f6c2f2SEnji Cooper *os << "(" << point.x << "," << point.y << ")"; 37128f6c2f2SEnji Cooper } 37228f6c2f2SEnji Cooper 37328f6c2f2SEnji Cooper int x; 37428f6c2f2SEnji Cooper int y; 37528f6c2f2SEnji Cooper}; 37628f6c2f2SEnji Cooper 37728f6c2f2SEnji Cooper// If you can't declare the function in the class it's important that PrintTo() 37828f6c2f2SEnji Cooper// is defined in the SAME namespace that defines Point. C++'s look-up rules 37928f6c2f2SEnji Cooper// rely on that. 38028f6c2f2SEnji Coopervoid PrintTo(const Point& point, std::ostream* os) { 38128f6c2f2SEnji Cooper *os << "(" << point.x << "," << point.y << ")"; 38228f6c2f2SEnji Cooper} 38328f6c2f2SEnji Cooper 38428f6c2f2SEnji Cooper} // namespace foo 38528f6c2f2SEnji Cooper``` 38628f6c2f2SEnji Cooper 38728f6c2f2SEnji CooperIf you have defined both `AbslStringify()` and `PrintTo()`, the latter will be 38828f6c2f2SEnji Cooperused by GoogleTest. This allows you to customize how the value appears in 38928f6c2f2SEnji CooperGoogleTest's output without affecting code that relies on the behavior of 39028f6c2f2SEnji Cooper`AbslStringify()`. 39128f6c2f2SEnji Cooper 39228f6c2f2SEnji CooperIf you have an existing `<<` operator and would like to define an 39328f6c2f2SEnji Cooper`AbslStringify()`, the latter will be used for GoogleTest printing. 39428f6c2f2SEnji Cooper 39528f6c2f2SEnji CooperIf you want to print a value `x` using GoogleTest's value printer yourself, just 39628f6c2f2SEnji Coopercall `::testing::PrintToString(x)`, which returns an `std::string`: 39728f6c2f2SEnji Cooper 39828f6c2f2SEnji Cooper```c++ 39928f6c2f2SEnji Coopervector<pair<Point, int> > point_ints = GetPointIntVector(); 40028f6c2f2SEnji Cooper 40128f6c2f2SEnji CooperEXPECT_TRUE(IsCorrectPointIntVector(point_ints)) 40228f6c2f2SEnji Cooper << "point_ints = " << testing::PrintToString(point_ints); 40328f6c2f2SEnji Cooper``` 40428f6c2f2SEnji Cooper 40528f6c2f2SEnji CooperFor more details regarding `AbslStringify()` and its integration with other 40628f6c2f2SEnji Cooperlibraries, see go/abslstringify. 40728f6c2f2SEnji Cooper 40828f6c2f2SEnji Cooper## Death Tests 40928f6c2f2SEnji Cooper 41028f6c2f2SEnji CooperIn many applications, there are assertions that can cause application failure if 41128f6c2f2SEnji Coopera condition is not met. These consistency checks, which ensure that the program 41228f6c2f2SEnji Cooperis in a known good state, are there to fail at the earliest possible time after 41328f6c2f2SEnji Coopersome program state is corrupted. If the assertion checks the wrong condition, 41428f6c2f2SEnji Cooperthen the program may proceed in an erroneous state, which could lead to memory 41528f6c2f2SEnji Coopercorruption, security holes, or worse. Hence it is vitally important to test that 41628f6c2f2SEnji Coopersuch assertion statements work as expected. 41728f6c2f2SEnji Cooper 41828f6c2f2SEnji CooperSince these precondition checks cause the processes to die, we call such tests 41928f6c2f2SEnji Cooper_death tests_. More generally, any test that checks that a program terminates 42028f6c2f2SEnji Cooper(except by throwing an exception) in an expected fashion is also a death test. 42128f6c2f2SEnji Cooper 42228f6c2f2SEnji CooperNote that if a piece of code throws an exception, we don't consider it "death" 42328f6c2f2SEnji Cooperfor the purpose of death tests, as the caller of the code could catch the 42428f6c2f2SEnji Cooperexception and avoid the crash. If you want to verify exceptions thrown by your 42528f6c2f2SEnji Coopercode, see [Exception Assertions](#ExceptionAssertions). 42628f6c2f2SEnji Cooper 42728f6c2f2SEnji CooperIf you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see 42828f6c2f2SEnji Cooper["Catching" Failures](#catching-failures). 42928f6c2f2SEnji Cooper 43028f6c2f2SEnji Cooper### How to Write a Death Test 43128f6c2f2SEnji Cooper 43228f6c2f2SEnji CooperGoogleTest provides assertion macros to support death tests. See 43328f6c2f2SEnji Cooper[Death Assertions](reference/assertions.md#death) in the Assertions Reference 43428f6c2f2SEnji Cooperfor details. 43528f6c2f2SEnji Cooper 43628f6c2f2SEnji CooperTo write a death test, simply use one of the macros inside your test function. 43728f6c2f2SEnji CooperFor example, 43828f6c2f2SEnji Cooper 43928f6c2f2SEnji Cooper```c++ 44028f6c2f2SEnji CooperTEST(MyDeathTest, Foo) { 44128f6c2f2SEnji Cooper // This death test uses a compound statement. 44228f6c2f2SEnji Cooper ASSERT_DEATH({ 44328f6c2f2SEnji Cooper int n = 5; 44428f6c2f2SEnji Cooper Foo(&n); 44528f6c2f2SEnji Cooper }, "Error on line .* of Foo()"); 44628f6c2f2SEnji Cooper} 44728f6c2f2SEnji Cooper 44828f6c2f2SEnji CooperTEST(MyDeathTest, NormalExit) { 44928f6c2f2SEnji Cooper EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); 45028f6c2f2SEnji Cooper} 45128f6c2f2SEnji Cooper 45228f6c2f2SEnji CooperTEST(MyDeathTest, KillProcess) { 45328f6c2f2SEnji Cooper EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL), 45428f6c2f2SEnji Cooper "Sending myself unblockable signal"); 45528f6c2f2SEnji Cooper} 45628f6c2f2SEnji Cooper``` 45728f6c2f2SEnji Cooper 45828f6c2f2SEnji Cooperverifies that: 45928f6c2f2SEnji Cooper 46028f6c2f2SEnji Cooper* calling `Foo(5)` causes the process to die with the given error message, 46128f6c2f2SEnji Cooper* calling `NormalExit()` causes the process to print `"Success"` to stderr and 46228f6c2f2SEnji Cooper exit with exit code 0, and 46328f6c2f2SEnji Cooper* calling `KillProcess()` kills the process with signal `SIGKILL`. 46428f6c2f2SEnji Cooper 46528f6c2f2SEnji CooperThe test function body may contain other assertions and statements as well, if 46628f6c2f2SEnji Coopernecessary. 46728f6c2f2SEnji Cooper 46828f6c2f2SEnji CooperNote that a death test only cares about three things: 46928f6c2f2SEnji Cooper 47028f6c2f2SEnji Cooper1. does `statement` abort or exit the process? 47128f6c2f2SEnji Cooper2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status 47228f6c2f2SEnji Cooper satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) 47328f6c2f2SEnji Cooper is the exit status non-zero? And 47428f6c2f2SEnji Cooper3. does the stderr output match `matcher`? 47528f6c2f2SEnji Cooper 47628f6c2f2SEnji CooperIn particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it 47728f6c2f2SEnji Cooperwill **not** cause the death test to fail, as GoogleTest assertions don't abort 47828f6c2f2SEnji Cooperthe process. 47928f6c2f2SEnji Cooper 48028f6c2f2SEnji Cooper### Death Test Naming 48128f6c2f2SEnji Cooper 48228f6c2f2SEnji Cooper{: .callout .important} 48328f6c2f2SEnji CooperIMPORTANT: We strongly recommend you to follow the convention of naming your 48428f6c2f2SEnji Cooper**test suite** (not test) `*DeathTest` when it contains a death test, as 48528f6c2f2SEnji Cooperdemonstrated in the above example. The 48628f6c2f2SEnji Cooper[Death Tests And Threads](#death-tests-and-threads) section below explains why. 48728f6c2f2SEnji Cooper 48828f6c2f2SEnji CooperIf a test fixture class is shared by normal tests and death tests, you can use 48928f6c2f2SEnji Cooper`using` or `typedef` to introduce an alias for the fixture class and avoid 49028f6c2f2SEnji Cooperduplicating its code: 49128f6c2f2SEnji Cooper 49228f6c2f2SEnji Cooper```c++ 49328f6c2f2SEnji Cooperclass FooTest : public testing::Test { ... }; 49428f6c2f2SEnji Cooper 49528f6c2f2SEnji Cooperusing FooDeathTest = FooTest; 49628f6c2f2SEnji Cooper 49728f6c2f2SEnji CooperTEST_F(FooTest, DoesThis) { 49828f6c2f2SEnji Cooper // normal test 49928f6c2f2SEnji Cooper} 50028f6c2f2SEnji Cooper 50128f6c2f2SEnji CooperTEST_F(FooDeathTest, DoesThat) { 50228f6c2f2SEnji Cooper // death test 50328f6c2f2SEnji Cooper} 50428f6c2f2SEnji Cooper``` 50528f6c2f2SEnji Cooper 50628f6c2f2SEnji Cooper### Regular Expression Syntax 50728f6c2f2SEnji Cooper 50828f6c2f2SEnji CooperWhen built with Bazel and using Abseil, GoogleTest uses the 50928f6c2f2SEnji Cooper[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX 51028f6c2f2SEnji Coopersystems (Linux, Cygwin, Mac), GoogleTest uses the 511*5ca8c28cSEnji Cooper[POSIX extended regular expression](https://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) 51228f6c2f2SEnji Coopersyntax. To learn about POSIX syntax, you may want to read this 513*5ca8c28cSEnji Cooper[Wikipedia entry](https://en.wikipedia.org/wiki/Regular_expression#POSIX_extended). 51428f6c2f2SEnji Cooper 51528f6c2f2SEnji CooperOn Windows, GoogleTest uses its own simple regular expression implementation. It 51628f6c2f2SEnji Cooperlacks many features. For example, we don't support union (`"x|y"`), grouping 51728f6c2f2SEnji Cooper(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among 51828f6c2f2SEnji Cooperothers. Below is what we do support (`A` denotes a literal character, period 51928f6c2f2SEnji Cooper(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular 52028f6c2f2SEnji Cooperexpressions.): 52128f6c2f2SEnji Cooper 52228f6c2f2SEnji CooperExpression | Meaning 52328f6c2f2SEnji Cooper---------- | -------------------------------------------------------------- 52428f6c2f2SEnji Cooper`c` | matches any literal character `c` 52528f6c2f2SEnji Cooper`\\d` | matches any decimal digit 52628f6c2f2SEnji Cooper`\\D` | matches any character that's not a decimal digit 52728f6c2f2SEnji Cooper`\\f` | matches `\f` 52828f6c2f2SEnji Cooper`\\n` | matches `\n` 52928f6c2f2SEnji Cooper`\\r` | matches `\r` 53028f6c2f2SEnji Cooper`\\s` | matches any ASCII whitespace, including `\n` 53128f6c2f2SEnji Cooper`\\S` | matches any character that's not a whitespace 53228f6c2f2SEnji Cooper`\\t` | matches `\t` 53328f6c2f2SEnji Cooper`\\v` | matches `\v` 53428f6c2f2SEnji Cooper`\\w` | matches any letter, `_`, or decimal digit 53528f6c2f2SEnji Cooper`\\W` | matches any character that `\\w` doesn't match 53628f6c2f2SEnji Cooper`\\c` | matches any literal character `c`, which must be a punctuation 53728f6c2f2SEnji Cooper`.` | matches any single character except `\n` 53828f6c2f2SEnji Cooper`A?` | matches 0 or 1 occurrences of `A` 53928f6c2f2SEnji Cooper`A*` | matches 0 or many occurrences of `A` 54028f6c2f2SEnji Cooper`A+` | matches 1 or many occurrences of `A` 54128f6c2f2SEnji Cooper`^` | matches the beginning of a string (not that of each line) 54228f6c2f2SEnji Cooper`$` | matches the end of a string (not that of each line) 54328f6c2f2SEnji Cooper`xy` | matches `x` followed by `y` 54428f6c2f2SEnji Cooper 54528f6c2f2SEnji CooperTo help you determine which capability is available on your system, GoogleTest 54628f6c2f2SEnji Cooperdefines macros to govern which regular expression it is using. The macros are: 54728f6c2f2SEnji Cooper`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death 54828f6c2f2SEnji Coopertests to work in all cases, you can either `#if` on these macros or use the more 54928f6c2f2SEnji Cooperlimited syntax only. 55028f6c2f2SEnji Cooper 55128f6c2f2SEnji Cooper### How It Works 55228f6c2f2SEnji Cooper 55328f6c2f2SEnji CooperSee [Death Assertions](reference/assertions.md#death) in the Assertions 55428f6c2f2SEnji CooperReference. 55528f6c2f2SEnji Cooper 55628f6c2f2SEnji Cooper### Death Tests And Threads 55728f6c2f2SEnji Cooper 55828f6c2f2SEnji CooperThe reason for the two death test styles has to do with thread safety. Due to 55928f6c2f2SEnji Cooperwell-known problems with forking in the presence of threads, death tests should 56028f6c2f2SEnji Cooperbe run in a single-threaded context. Sometimes, however, it isn't feasible to 56128f6c2f2SEnji Cooperarrange that kind of environment. For example, statically-initialized modules 56228f6c2f2SEnji Coopermay start threads before main is ever reached. Once threads have been created, 56328f6c2f2SEnji Cooperit may be difficult or impossible to clean them up. 56428f6c2f2SEnji Cooper 56528f6c2f2SEnji CooperGoogleTest has three features intended to raise awareness of threading issues. 56628f6c2f2SEnji Cooper 56728f6c2f2SEnji Cooper1. A warning is emitted if multiple threads are running when a death test is 56828f6c2f2SEnji Cooper encountered. 56928f6c2f2SEnji Cooper2. Test suites with a name ending in "DeathTest" are run before all other 57028f6c2f2SEnji Cooper tests. 57128f6c2f2SEnji Cooper3. It uses `clone()` instead of `fork()` to spawn the child process on Linux 57228f6c2f2SEnji Cooper (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely 57328f6c2f2SEnji Cooper to cause the child to hang when the parent process has multiple threads. 57428f6c2f2SEnji Cooper 57528f6c2f2SEnji CooperIt's perfectly fine to create threads inside a death test statement; they are 57628f6c2f2SEnji Cooperexecuted in a separate process and cannot affect the parent. 57728f6c2f2SEnji Cooper 57828f6c2f2SEnji Cooper### Death Test Styles 57928f6c2f2SEnji Cooper 58028f6c2f2SEnji CooperThe "threadsafe" death test style was introduced in order to help mitigate the 58128f6c2f2SEnji Cooperrisks of testing in a possibly multithreaded environment. It trades increased 58228f6c2f2SEnji Coopertest execution time (potentially dramatically so) for improved thread safety. 58328f6c2f2SEnji Cooper 58428f6c2f2SEnji CooperThe automated testing framework does not set the style flag. You can choose a 58528f6c2f2SEnji Cooperparticular style of death tests by setting the flag programmatically: 58628f6c2f2SEnji Cooper 58728f6c2f2SEnji Cooper```c++ 58828f6c2f2SEnji CooperGTEST_FLAG_SET(death_test_style, "threadsafe"); 58928f6c2f2SEnji Cooper``` 59028f6c2f2SEnji Cooper 59128f6c2f2SEnji CooperYou can do this in `main()` to set the style for all death tests in the binary, 59228f6c2f2SEnji Cooperor in individual tests. Recall that flags are saved before running each test and 59328f6c2f2SEnji Cooperrestored afterwards, so you need not do that yourself. For example: 59428f6c2f2SEnji Cooper 59528f6c2f2SEnji Cooper```c++ 59628f6c2f2SEnji Cooperint main(int argc, char** argv) { 59728f6c2f2SEnji Cooper testing::InitGoogleTest(&argc, argv); 59828f6c2f2SEnji Cooper GTEST_FLAG_SET(death_test_style, "fast"); 59928f6c2f2SEnji Cooper return RUN_ALL_TESTS(); 60028f6c2f2SEnji Cooper} 60128f6c2f2SEnji Cooper 60228f6c2f2SEnji CooperTEST(MyDeathTest, TestOne) { 60328f6c2f2SEnji Cooper GTEST_FLAG_SET(death_test_style, "threadsafe"); 60428f6c2f2SEnji Cooper // This test is run in the "threadsafe" style: 60528f6c2f2SEnji Cooper ASSERT_DEATH(ThisShouldDie(), ""); 60628f6c2f2SEnji Cooper} 60728f6c2f2SEnji Cooper 60828f6c2f2SEnji CooperTEST(MyDeathTest, TestTwo) { 60928f6c2f2SEnji Cooper // This test is run in the "fast" style: 61028f6c2f2SEnji Cooper ASSERT_DEATH(ThisShouldDie(), ""); 61128f6c2f2SEnji Cooper} 61228f6c2f2SEnji Cooper``` 61328f6c2f2SEnji Cooper 61428f6c2f2SEnji Cooper### Caveats 61528f6c2f2SEnji Cooper 61628f6c2f2SEnji CooperThe `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If 61728f6c2f2SEnji Cooperit leaves the current function via a `return` statement or by throwing an 61828f6c2f2SEnji Cooperexception, the death test is considered to have failed. Some GoogleTest macros 61928f6c2f2SEnji Coopermay return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid 62028f6c2f2SEnji Cooperthem in `statement`. 62128f6c2f2SEnji Cooper 62228f6c2f2SEnji CooperSince `statement` runs in the child process, any in-memory side effect (e.g. 62328f6c2f2SEnji Coopermodifying a variable, releasing memory, etc) it causes will *not* be observable 62428f6c2f2SEnji Cooperin the parent process. In particular, if you release memory in a death test, 62528f6c2f2SEnji Cooperyour program will fail the heap check as the parent process will never see the 62628f6c2f2SEnji Coopermemory reclaimed. To solve this problem, you can 62728f6c2f2SEnji Cooper 62828f6c2f2SEnji Cooper1. try not to free memory in a death test; 62928f6c2f2SEnji Cooper2. free the memory again in the parent process; or 63028f6c2f2SEnji Cooper3. do not use the heap checker in your program. 63128f6c2f2SEnji Cooper 63228f6c2f2SEnji CooperDue to an implementation detail, you cannot place multiple death test assertions 63328f6c2f2SEnji Cooperon the same line; otherwise, compilation will fail with an unobvious error 63428f6c2f2SEnji Coopermessage. 63528f6c2f2SEnji Cooper 63628f6c2f2SEnji CooperDespite the improved thread safety afforded by the "threadsafe" style of death 63728f6c2f2SEnji Coopertest, thread problems such as deadlock are still possible in the presence of 63828f6c2f2SEnji Cooperhandlers registered with `pthread_atfork(3)`. 63928f6c2f2SEnji Cooper 64028f6c2f2SEnji Cooper## Using Assertions in Sub-routines 64128f6c2f2SEnji Cooper 64228f6c2f2SEnji Cooper{: .callout .note} 64328f6c2f2SEnji CooperNote: If you want to put a series of test assertions in a subroutine to check 64428f6c2f2SEnji Cooperfor a complex condition, consider using 64528f6c2f2SEnji Cooper[a custom GMock matcher](gmock_cook_book.md#NewMatchers) instead. This lets you 64628f6c2f2SEnji Cooperprovide a more readable error message in case of failure and avoid all of the 64728f6c2f2SEnji Cooperissues described below. 64828f6c2f2SEnji Cooper 64928f6c2f2SEnji Cooper### Adding Traces to Assertions 65028f6c2f2SEnji Cooper 65128f6c2f2SEnji CooperIf a test sub-routine is called from several places, when an assertion inside it 65228f6c2f2SEnji Cooperfails, it can be hard to tell which invocation of the sub-routine the failure is 65328f6c2f2SEnji Cooperfrom. You can alleviate this problem using extra logging or custom failure 65428f6c2f2SEnji Coopermessages, but that usually clutters up your tests. A better solution is to use 65528f6c2f2SEnji Cooperthe `SCOPED_TRACE` macro or the `ScopedTrace` utility: 65628f6c2f2SEnji Cooper 65728f6c2f2SEnji Cooper```c++ 65828f6c2f2SEnji CooperSCOPED_TRACE(message); 65928f6c2f2SEnji Cooper``` 66028f6c2f2SEnji Cooper 66128f6c2f2SEnji Cooper```c++ 66228f6c2f2SEnji CooperScopedTrace trace("file_path", line_number, message); 66328f6c2f2SEnji Cooper``` 66428f6c2f2SEnji Cooper 66528f6c2f2SEnji Cooperwhere `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE` 66628f6c2f2SEnji Coopermacro will cause the current file name, line number, and the given message to be 66728f6c2f2SEnji Cooperadded in every failure message. `ScopedTrace` accepts explicit file name and 66828f6c2f2SEnji Cooperline number in arguments, which is useful for writing test helpers. The effect 66928f6c2f2SEnji Cooperwill be undone when the control leaves the current lexical scope. 67028f6c2f2SEnji Cooper 67128f6c2f2SEnji CooperFor example, 67228f6c2f2SEnji Cooper 67328f6c2f2SEnji Cooper```c++ 67428f6c2f2SEnji Cooper10: void Sub1(int n) { 67528f6c2f2SEnji Cooper11: EXPECT_EQ(Bar(n), 1); 67628f6c2f2SEnji Cooper12: EXPECT_EQ(Bar(n + 1), 2); 67728f6c2f2SEnji Cooper13: } 67828f6c2f2SEnji Cooper14: 67928f6c2f2SEnji Cooper15: TEST(FooTest, Bar) { 68028f6c2f2SEnji Cooper16: { 68128f6c2f2SEnji Cooper17: SCOPED_TRACE("A"); // This trace point will be included in 68228f6c2f2SEnji Cooper18: // every failure in this scope. 68328f6c2f2SEnji Cooper19: Sub1(1); 68428f6c2f2SEnji Cooper20: } 68528f6c2f2SEnji Cooper21: // Now it won't. 68628f6c2f2SEnji Cooper22: Sub1(9); 68728f6c2f2SEnji Cooper23: } 68828f6c2f2SEnji Cooper``` 68928f6c2f2SEnji Cooper 69028f6c2f2SEnji Coopercould result in messages like these: 69128f6c2f2SEnji Cooper 69228f6c2f2SEnji Cooper```none 69328f6c2f2SEnji Cooperpath/to/foo_test.cc:11: Failure 69428f6c2f2SEnji CooperValue of: Bar(n) 69528f6c2f2SEnji CooperExpected: 1 69628f6c2f2SEnji Cooper Actual: 2 69728f6c2f2SEnji CooperGoogle Test trace: 69828f6c2f2SEnji Cooperpath/to/foo_test.cc:17: A 69928f6c2f2SEnji Cooper 70028f6c2f2SEnji Cooperpath/to/foo_test.cc:12: Failure 70128f6c2f2SEnji CooperValue of: Bar(n + 1) 70228f6c2f2SEnji CooperExpected: 2 70328f6c2f2SEnji Cooper Actual: 3 70428f6c2f2SEnji Cooper``` 70528f6c2f2SEnji Cooper 70628f6c2f2SEnji CooperWithout the trace, it would've been difficult to know which invocation of 70728f6c2f2SEnji Cooper`Sub1()` the two failures come from respectively. (You could add an extra 70828f6c2f2SEnji Coopermessage to each assertion in `Sub1()` to indicate the value of `n`, but that's 70928f6c2f2SEnji Coopertedious.) 71028f6c2f2SEnji Cooper 71128f6c2f2SEnji CooperSome tips on using `SCOPED_TRACE`: 71228f6c2f2SEnji Cooper 71328f6c2f2SEnji Cooper1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the 71428f6c2f2SEnji Cooper beginning of a sub-routine, instead of at each call site. 71528f6c2f2SEnji Cooper2. When calling sub-routines inside a loop, make the loop iterator part of the 71628f6c2f2SEnji Cooper message in `SCOPED_TRACE` such that you can know which iteration the failure 71728f6c2f2SEnji Cooper is from. 71828f6c2f2SEnji Cooper3. Sometimes the line number of the trace point is enough for identifying the 71928f6c2f2SEnji Cooper particular invocation of a sub-routine. In this case, you don't have to 72028f6c2f2SEnji Cooper choose a unique message for `SCOPED_TRACE`. You can simply use `""`. 72128f6c2f2SEnji Cooper4. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer 72228f6c2f2SEnji Cooper scope. In this case, all active trace points will be included in the failure 72328f6c2f2SEnji Cooper messages, in reverse order they are encountered. 72428f6c2f2SEnji Cooper5. The trace dump is clickable in Emacs - hit `return` on a line number and 72528f6c2f2SEnji Cooper you'll be taken to that line in the source file! 72628f6c2f2SEnji Cooper 72728f6c2f2SEnji Cooper### Propagating Fatal Failures 72828f6c2f2SEnji Cooper 72928f6c2f2SEnji CooperA common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that 73028f6c2f2SEnji Cooperwhen they fail they only abort the _current function_, not the entire test. For 73128f6c2f2SEnji Cooperexample, the following test will segfault: 73228f6c2f2SEnji Cooper 73328f6c2f2SEnji Cooper```c++ 73428f6c2f2SEnji Coopervoid Subroutine() { 73528f6c2f2SEnji Cooper // Generates a fatal failure and aborts the current function. 73628f6c2f2SEnji Cooper ASSERT_EQ(1, 2); 73728f6c2f2SEnji Cooper 73828f6c2f2SEnji Cooper // The following won't be executed. 73928f6c2f2SEnji Cooper ... 74028f6c2f2SEnji Cooper} 74128f6c2f2SEnji Cooper 74228f6c2f2SEnji CooperTEST(FooTest, Bar) { 74328f6c2f2SEnji Cooper Subroutine(); // The intended behavior is for the fatal failure 74428f6c2f2SEnji Cooper // in Subroutine() to abort the entire test. 74528f6c2f2SEnji Cooper 74628f6c2f2SEnji Cooper // The actual behavior: the function goes on after Subroutine() returns. 74728f6c2f2SEnji Cooper int* p = nullptr; 74828f6c2f2SEnji Cooper *p = 3; // Segfault! 74928f6c2f2SEnji Cooper} 75028f6c2f2SEnji Cooper``` 75128f6c2f2SEnji Cooper 75228f6c2f2SEnji CooperTo alleviate this, GoogleTest provides three different solutions. You could use 75328f6c2f2SEnji Coopereither exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the 75428f6c2f2SEnji Cooper`HasFatalFailure()` function. They are described in the following two 75528f6c2f2SEnji Coopersubsections. 75628f6c2f2SEnji Cooper 75728f6c2f2SEnji Cooper#### Asserting on Subroutines with an exception 75828f6c2f2SEnji Cooper 75928f6c2f2SEnji CooperThe following code can turn ASSERT-failure into an exception: 76028f6c2f2SEnji Cooper 76128f6c2f2SEnji Cooper```c++ 76228f6c2f2SEnji Cooperclass ThrowListener : public testing::EmptyTestEventListener { 76328f6c2f2SEnji Cooper void OnTestPartResult(const testing::TestPartResult& result) override { 76428f6c2f2SEnji Cooper if (result.type() == testing::TestPartResult::kFatalFailure) { 76528f6c2f2SEnji Cooper throw testing::AssertionException(result); 76628f6c2f2SEnji Cooper } 76728f6c2f2SEnji Cooper } 76828f6c2f2SEnji Cooper}; 76928f6c2f2SEnji Cooperint main(int argc, char** argv) { 77028f6c2f2SEnji Cooper ... 77128f6c2f2SEnji Cooper testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener); 77228f6c2f2SEnji Cooper return RUN_ALL_TESTS(); 77328f6c2f2SEnji Cooper} 77428f6c2f2SEnji Cooper``` 77528f6c2f2SEnji Cooper 77628f6c2f2SEnji CooperThis listener should be added after other listeners if you have any, otherwise 77728f6c2f2SEnji Cooperthey won't see failed `OnTestPartResult`. 77828f6c2f2SEnji Cooper 77928f6c2f2SEnji Cooper#### Asserting on Subroutines 78028f6c2f2SEnji Cooper 78128f6c2f2SEnji CooperAs shown above, if your test calls a subroutine that has an `ASSERT_*` failure 78228f6c2f2SEnji Cooperin it, the test will continue after the subroutine returns. This may not be what 78328f6c2f2SEnji Cooperyou want. 78428f6c2f2SEnji Cooper 78528f6c2f2SEnji CooperOften people want fatal failures to propagate like exceptions. For that 78628f6c2f2SEnji CooperGoogleTest offers the following macros: 78728f6c2f2SEnji Cooper 78828f6c2f2SEnji CooperFatal assertion | Nonfatal assertion | Verifies 78928f6c2f2SEnji Cooper------------------------------------- | ------------------------------------- | -------- 79028f6c2f2SEnji Cooper`ASSERT_NO_FATAL_FAILURE(statement);` | `EXPECT_NO_FATAL_FAILURE(statement);` | `statement` doesn't generate any new fatal failures in the current thread. 79128f6c2f2SEnji Cooper 79228f6c2f2SEnji CooperOnly failures in the thread that executes the assertion are checked to determine 79328f6c2f2SEnji Cooperthe result of this type of assertions. If `statement` creates new threads, 79428f6c2f2SEnji Cooperfailures in these threads are ignored. 79528f6c2f2SEnji Cooper 79628f6c2f2SEnji CooperExamples: 79728f6c2f2SEnji Cooper 79828f6c2f2SEnji Cooper```c++ 79928f6c2f2SEnji CooperASSERT_NO_FATAL_FAILURE(Foo()); 80028f6c2f2SEnji Cooper 80128f6c2f2SEnji Cooperint i; 80228f6c2f2SEnji CooperEXPECT_NO_FATAL_FAILURE({ 80328f6c2f2SEnji Cooper i = Bar(); 80428f6c2f2SEnji Cooper}); 80528f6c2f2SEnji Cooper``` 80628f6c2f2SEnji Cooper 80728f6c2f2SEnji CooperAssertions from multiple threads are currently not supported on Windows. 80828f6c2f2SEnji Cooper 80928f6c2f2SEnji Cooper#### Checking for Failures in the Current Test 81028f6c2f2SEnji Cooper 81128f6c2f2SEnji Cooper`HasFatalFailure()` in the `::testing::Test` class returns `true` if an 81228f6c2f2SEnji Cooperassertion in the current test has suffered a fatal failure. This allows 81328f6c2f2SEnji Cooperfunctions to catch fatal failures in a sub-routine and return early. 81428f6c2f2SEnji Cooper 81528f6c2f2SEnji Cooper```c++ 81628f6c2f2SEnji Cooperclass Test { 81728f6c2f2SEnji Cooper public: 81828f6c2f2SEnji Cooper ... 81928f6c2f2SEnji Cooper static bool HasFatalFailure(); 82028f6c2f2SEnji Cooper}; 82128f6c2f2SEnji Cooper``` 82228f6c2f2SEnji Cooper 82328f6c2f2SEnji CooperThe typical usage, which basically simulates the behavior of a thrown exception, 82428f6c2f2SEnji Cooperis: 82528f6c2f2SEnji Cooper 82628f6c2f2SEnji Cooper```c++ 82728f6c2f2SEnji CooperTEST(FooTest, Bar) { 82828f6c2f2SEnji Cooper Subroutine(); 82928f6c2f2SEnji Cooper // Aborts if Subroutine() had a fatal failure. 83028f6c2f2SEnji Cooper if (HasFatalFailure()) return; 83128f6c2f2SEnji Cooper 83228f6c2f2SEnji Cooper // The following won't be executed. 83328f6c2f2SEnji Cooper ... 83428f6c2f2SEnji Cooper} 83528f6c2f2SEnji Cooper``` 83628f6c2f2SEnji Cooper 83728f6c2f2SEnji CooperIf `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test 83828f6c2f2SEnji Cooperfixture, you must add the `::testing::Test::` prefix, as in: 83928f6c2f2SEnji Cooper 84028f6c2f2SEnji Cooper```c++ 84128f6c2f2SEnji Cooperif (testing::Test::HasFatalFailure()) return; 84228f6c2f2SEnji Cooper``` 84328f6c2f2SEnji Cooper 84428f6c2f2SEnji CooperSimilarly, `HasNonfatalFailure()` returns `true` if the current test has at 84528f6c2f2SEnji Cooperleast one non-fatal failure, and `HasFailure()` returns `true` if the current 84628f6c2f2SEnji Coopertest has at least one failure of either kind. 84728f6c2f2SEnji Cooper 84828f6c2f2SEnji Cooper## Logging Additional Information 84928f6c2f2SEnji Cooper 85028f6c2f2SEnji CooperIn your test code, you can call `RecordProperty("key", value)` to log additional 85128f6c2f2SEnji Cooperinformation, where `value` can be either a string or an `int`. The *last* value 85228f6c2f2SEnji Cooperrecorded for a key will be emitted to the 85328f6c2f2SEnji Cooper[XML output](#generating-an-xml-report) if you specify one. For example, the 85428f6c2f2SEnji Coopertest 85528f6c2f2SEnji Cooper 85628f6c2f2SEnji Cooper```c++ 85728f6c2f2SEnji CooperTEST_F(WidgetUsageTest, MinAndMaxWidgets) { 85828f6c2f2SEnji Cooper RecordProperty("MaximumWidgets", ComputeMaxUsage()); 85928f6c2f2SEnji Cooper RecordProperty("MinimumWidgets", ComputeMinUsage()); 86028f6c2f2SEnji Cooper} 86128f6c2f2SEnji Cooper``` 86228f6c2f2SEnji Cooper 86328f6c2f2SEnji Cooperwill output XML like this: 86428f6c2f2SEnji Cooper 86528f6c2f2SEnji Cooper```xml 86628f6c2f2SEnji Cooper ... 86728f6c2f2SEnji Cooper <testcase name="MinAndMaxWidgets" file="test.cpp" line="1" status="run" time="0.006" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" /> 86828f6c2f2SEnji Cooper ... 86928f6c2f2SEnji Cooper``` 87028f6c2f2SEnji Cooper 87128f6c2f2SEnji Cooper{: .callout .note} 87228f6c2f2SEnji Cooper> NOTE: 87328f6c2f2SEnji Cooper> 87428f6c2f2SEnji Cooper> * `RecordProperty()` is a static member of the `Test` class. Therefore it 87528f6c2f2SEnji Cooper> needs to be prefixed with `::testing::Test::` if used outside of the 87628f6c2f2SEnji Cooper> `TEST` body and the test fixture class. 87728f6c2f2SEnji Cooper> * *`key`* must be a valid XML attribute name, and cannot conflict with the 87828f6c2f2SEnji Cooper> ones already used by GoogleTest (`name`, `status`, `time`, `classname`, 87928f6c2f2SEnji Cooper> `type_param`, and `value_param`). 88028f6c2f2SEnji Cooper> * Calling `RecordProperty()` outside of the lifespan of a test is allowed. 88128f6c2f2SEnji Cooper> If it's called outside of a test but between a test suite's 88228f6c2f2SEnji Cooper> `SetUpTestSuite()` and `TearDownTestSuite()` methods, it will be 88328f6c2f2SEnji Cooper> attributed to the XML element for the test suite. If it's called outside 88428f6c2f2SEnji Cooper> of all test suites (e.g. in a test environment), it will be attributed to 88528f6c2f2SEnji Cooper> the top-level XML element. 88628f6c2f2SEnji Cooper 88728f6c2f2SEnji Cooper## Sharing Resources Between Tests in the Same Test Suite 88828f6c2f2SEnji Cooper 88928f6c2f2SEnji CooperGoogleTest creates a new test fixture object for each test in order to make 89028f6c2f2SEnji Coopertests independent and easier to debug. However, sometimes tests use resources 89128f6c2f2SEnji Cooperthat are expensive to set up, making the one-copy-per-test model prohibitively 89228f6c2f2SEnji Cooperexpensive. 89328f6c2f2SEnji Cooper 89428f6c2f2SEnji CooperIf the tests don't change the resource, there's no harm in their sharing a 89528f6c2f2SEnji Coopersingle resource copy. So, in addition to per-test set-up/tear-down, GoogleTest 89628f6c2f2SEnji Cooperalso supports per-test-suite set-up/tear-down. To use it: 89728f6c2f2SEnji Cooper 89828f6c2f2SEnji Cooper1. In your test fixture class (say `FooTest` ), declare as `static` some member 89928f6c2f2SEnji Cooper variables to hold the shared resources. 90028f6c2f2SEnji Cooper2. Outside your test fixture class (typically just below it), define those 90128f6c2f2SEnji Cooper member variables, optionally giving them initial values. 902*5ca8c28cSEnji Cooper3. In the same test fixture class, define a public member function `static void 903*5ca8c28cSEnji Cooper SetUpTestSuite()` (remember not to spell it as **`SetupTestSuite`** with a 904*5ca8c28cSEnji Cooper small `u`!) to set up the shared resources and a `static void 905*5ca8c28cSEnji Cooper TearDownTestSuite()` function to tear them down. 90628f6c2f2SEnji Cooper 90728f6c2f2SEnji CooperThat's it! GoogleTest automatically calls `SetUpTestSuite()` before running the 90828f6c2f2SEnji Cooper*first test* in the `FooTest` test suite (i.e. before creating the first 90928f6c2f2SEnji Cooper`FooTest` object), and calls `TearDownTestSuite()` after running the *last test* 91028f6c2f2SEnji Cooperin it (i.e. after deleting the last `FooTest` object). In between, the tests can 91128f6c2f2SEnji Cooperuse the shared resources. 91228f6c2f2SEnji Cooper 91328f6c2f2SEnji CooperRemember that the test order is undefined, so your code can't depend on a test 91428f6c2f2SEnji Cooperpreceding or following another. Also, the tests must either not modify the state 91528f6c2f2SEnji Cooperof any shared resource, or, if they do modify the state, they must restore the 91628f6c2f2SEnji Cooperstate to its original value before passing control to the next test. 91728f6c2f2SEnji Cooper 91828f6c2f2SEnji CooperNote that `SetUpTestSuite()` may be called multiple times for a test fixture 91928f6c2f2SEnji Cooperclass that has derived classes, so you should not expect code in the function 92028f6c2f2SEnji Cooperbody to be run only once. Also, derived classes still have access to shared 92128f6c2f2SEnji Cooperresources defined as static members, so careful consideration is needed when 92228f6c2f2SEnji Coopermanaging shared resources to avoid memory leaks if shared resources are not 92328f6c2f2SEnji Cooperproperly cleaned up in `TearDownTestSuite()`. 92428f6c2f2SEnji Cooper 92528f6c2f2SEnji CooperHere's an example of per-test-suite set-up and tear-down: 92628f6c2f2SEnji Cooper 92728f6c2f2SEnji Cooper```c++ 92828f6c2f2SEnji Cooperclass FooTest : public testing::Test { 92928f6c2f2SEnji Cooper protected: 93028f6c2f2SEnji Cooper // Per-test-suite set-up. 93128f6c2f2SEnji Cooper // Called before the first test in this test suite. 93228f6c2f2SEnji Cooper // Can be omitted if not needed. 93328f6c2f2SEnji Cooper static void SetUpTestSuite() { 93428f6c2f2SEnji Cooper shared_resource_ = new ...; 93528f6c2f2SEnji Cooper 93628f6c2f2SEnji Cooper // If `shared_resource_` is **not deleted** in `TearDownTestSuite()`, 93728f6c2f2SEnji Cooper // reallocation should be prevented because `SetUpTestSuite()` may be called 93828f6c2f2SEnji Cooper // in subclasses of FooTest and lead to memory leak. 93928f6c2f2SEnji Cooper // 94028f6c2f2SEnji Cooper // if (shared_resource_ == nullptr) { 94128f6c2f2SEnji Cooper // shared_resource_ = new ...; 94228f6c2f2SEnji Cooper // } 94328f6c2f2SEnji Cooper } 94428f6c2f2SEnji Cooper 94528f6c2f2SEnji Cooper // Per-test-suite tear-down. 94628f6c2f2SEnji Cooper // Called after the last test in this test suite. 94728f6c2f2SEnji Cooper // Can be omitted if not needed. 94828f6c2f2SEnji Cooper static void TearDownTestSuite() { 94928f6c2f2SEnji Cooper delete shared_resource_; 95028f6c2f2SEnji Cooper shared_resource_ = nullptr; 95128f6c2f2SEnji Cooper } 95228f6c2f2SEnji Cooper 95328f6c2f2SEnji Cooper // You can define per-test set-up logic as usual. 95428f6c2f2SEnji Cooper void SetUp() override { ... } 95528f6c2f2SEnji Cooper 95628f6c2f2SEnji Cooper // You can define per-test tear-down logic as usual. 95728f6c2f2SEnji Cooper void TearDown() override { ... } 95828f6c2f2SEnji Cooper 95928f6c2f2SEnji Cooper // Some expensive resource shared by all tests. 96028f6c2f2SEnji Cooper static T* shared_resource_; 96128f6c2f2SEnji Cooper}; 96228f6c2f2SEnji Cooper 96328f6c2f2SEnji CooperT* FooTest::shared_resource_ = nullptr; 96428f6c2f2SEnji Cooper 96528f6c2f2SEnji CooperTEST_F(FooTest, Test1) { 96628f6c2f2SEnji Cooper ... you can refer to shared_resource_ here ... 96728f6c2f2SEnji Cooper} 96828f6c2f2SEnji Cooper 96928f6c2f2SEnji CooperTEST_F(FooTest, Test2) { 97028f6c2f2SEnji Cooper ... you can refer to shared_resource_ here ... 97128f6c2f2SEnji Cooper} 97228f6c2f2SEnji Cooper``` 97328f6c2f2SEnji Cooper 97428f6c2f2SEnji Cooper{: .callout .note} 97528f6c2f2SEnji CooperNOTE: Though the above code declares `SetUpTestSuite()` protected, it may 97628f6c2f2SEnji Coopersometimes be necessary to declare it public, such as when using it with 97728f6c2f2SEnji Cooper`TEST_P`. 97828f6c2f2SEnji Cooper 97928f6c2f2SEnji Cooper## Global Set-Up and Tear-Down 98028f6c2f2SEnji Cooper 98128f6c2f2SEnji CooperJust as you can do set-up and tear-down at the test level and the test suite 98228f6c2f2SEnji Cooperlevel, you can also do it at the test program level. Here's how. 98328f6c2f2SEnji Cooper 98428f6c2f2SEnji CooperFirst, you subclass the `::testing::Environment` class to define a test 98528f6c2f2SEnji Cooperenvironment, which knows how to set-up and tear-down: 98628f6c2f2SEnji Cooper 98728f6c2f2SEnji Cooper```c++ 98828f6c2f2SEnji Cooperclass Environment : public ::testing::Environment { 98928f6c2f2SEnji Cooper public: 99028f6c2f2SEnji Cooper ~Environment() override {} 99128f6c2f2SEnji Cooper 99228f6c2f2SEnji Cooper // Override this to define how to set up the environment. 99328f6c2f2SEnji Cooper void SetUp() override {} 99428f6c2f2SEnji Cooper 99528f6c2f2SEnji Cooper // Override this to define how to tear down the environment. 99628f6c2f2SEnji Cooper void TearDown() override {} 99728f6c2f2SEnji Cooper}; 99828f6c2f2SEnji Cooper``` 99928f6c2f2SEnji Cooper 100028f6c2f2SEnji CooperThen, you register an instance of your environment class with GoogleTest by 100128f6c2f2SEnji Coopercalling the `::testing::AddGlobalTestEnvironment()` function: 100228f6c2f2SEnji Cooper 100328f6c2f2SEnji Cooper```c++ 100428f6c2f2SEnji CooperEnvironment* AddGlobalTestEnvironment(Environment* env); 100528f6c2f2SEnji Cooper``` 100628f6c2f2SEnji Cooper 1007*5ca8c28cSEnji CooperNow, when `RUN_ALL_TESTS()` is invoked, it first calls the `SetUp()` method. The 1008*5ca8c28cSEnji Coopertests are then executed, provided that none of the environments have reported 1009*5ca8c28cSEnji Cooperfatal failures and `GTEST_SKIP()` has not been invoked. Finally, `TearDown()` is 1010*5ca8c28cSEnji Coopercalled. 1011*5ca8c28cSEnji Cooper 1012*5ca8c28cSEnji CooperNote that `SetUp()` and `TearDown()` are only invoked if there is at least one 1013*5ca8c28cSEnji Coopertest to be performed. Importantly, `TearDown()` is executed even if the test is 1014*5ca8c28cSEnji Coopernot run due to a fatal failure or `GTEST_SKIP()`. 1015*5ca8c28cSEnji Cooper 1016*5ca8c28cSEnji CooperCalling `SetUp()` and `TearDown()` for each iteration depends on the flag 1017*5ca8c28cSEnji Cooper`gtest_recreate_environments_when_repeating`. `SetUp()` and `TearDown()` are 1018*5ca8c28cSEnji Coopercalled for each environment object when the object is recreated for each 1019*5ca8c28cSEnji Cooperiteration. However, if test environments are not recreated for each iteration, 1020*5ca8c28cSEnji Cooper`SetUp()` is called only on the first iteration, and `TearDown()` is called only 1021*5ca8c28cSEnji Cooperon the last iteration. 102228f6c2f2SEnji Cooper 102328f6c2f2SEnji CooperIt's OK to register multiple environment objects. In this suite, their `SetUp()` 102428f6c2f2SEnji Cooperwill be called in the order they are registered, and their `TearDown()` will be 102528f6c2f2SEnji Coopercalled in the reverse order. 102628f6c2f2SEnji Cooper 102728f6c2f2SEnji CooperNote that GoogleTest takes ownership of the registered environment objects. 102828f6c2f2SEnji CooperTherefore **do not delete them** by yourself. 102928f6c2f2SEnji Cooper 103028f6c2f2SEnji CooperYou should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, 103128f6c2f2SEnji Cooperprobably in `main()`. If you use `gtest_main`, you need to call this before 103228f6c2f2SEnji Cooper`main()` starts for it to take effect. One way to do this is to define a global 103328f6c2f2SEnji Coopervariable like this: 103428f6c2f2SEnji Cooper 103528f6c2f2SEnji Cooper```c++ 103628f6c2f2SEnji Coopertesting::Environment* const foo_env = 103728f6c2f2SEnji Cooper testing::AddGlobalTestEnvironment(new FooEnvironment); 103828f6c2f2SEnji Cooper``` 103928f6c2f2SEnji Cooper 104028f6c2f2SEnji CooperHowever, we strongly recommend you to write your own `main()` and call 104128f6c2f2SEnji Cooper`AddGlobalTestEnvironment()` there, as relying on initialization of global 104228f6c2f2SEnji Coopervariables makes the code harder to read and may cause problems when you register 104328f6c2f2SEnji Coopermultiple environments from different translation units and the environments have 104428f6c2f2SEnji Cooperdependencies among them (remember that the compiler doesn't guarantee the order 104528f6c2f2SEnji Cooperin which global variables from different translation units are initialized). 104628f6c2f2SEnji Cooper 104728f6c2f2SEnji Cooper## Value-Parameterized Tests 104828f6c2f2SEnji Cooper 104928f6c2f2SEnji Cooper*Value-parameterized tests* allow you to test your code with different 105028f6c2f2SEnji Cooperparameters without writing multiple copies of the same test. This is useful in a 105128f6c2f2SEnji Coopernumber of situations, for example: 105228f6c2f2SEnji Cooper 105328f6c2f2SEnji Cooper* You have a piece of code whose behavior is affected by one or more 105428f6c2f2SEnji Cooper command-line flags. You want to make sure your code performs correctly for 105528f6c2f2SEnji Cooper various values of those flags. 105628f6c2f2SEnji Cooper* You want to test different implementations of an OO interface. 105728f6c2f2SEnji Cooper* You want to test your code over various inputs (a.k.a. data-driven testing). 105828f6c2f2SEnji Cooper This feature is easy to abuse, so please exercise your good sense when doing 105928f6c2f2SEnji Cooper it! 106028f6c2f2SEnji Cooper 106128f6c2f2SEnji Cooper### How to Write Value-Parameterized Tests 106228f6c2f2SEnji Cooper 106328f6c2f2SEnji CooperTo write value-parameterized tests, first you should define a fixture class. It 106428f6c2f2SEnji Coopermust be derived from both `testing::Test` and `testing::WithParamInterface<T>` 106528f6c2f2SEnji Cooper(the latter is a pure interface), where `T` is the type of your parameter 106628f6c2f2SEnji Coopervalues. For convenience, you can just derive the fixture class from 106728f6c2f2SEnji Cooper`testing::TestWithParam<T>`, which itself is derived from both `testing::Test` 106828f6c2f2SEnji Cooperand `testing::WithParamInterface<T>`. `T` can be any copyable type. If it's a 106928f6c2f2SEnji Cooperraw pointer, you are responsible for managing the lifespan of the pointed 107028f6c2f2SEnji Coopervalues. 107128f6c2f2SEnji Cooper 107228f6c2f2SEnji Cooper{: .callout .note} 107328f6c2f2SEnji CooperNOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()` 107428f6c2f2SEnji Cooperthey must be declared **public** rather than **protected** in order to use 107528f6c2f2SEnji Cooper`TEST_P`. 107628f6c2f2SEnji Cooper 107728f6c2f2SEnji Cooper```c++ 107828f6c2f2SEnji Cooperclass FooTest : 107928f6c2f2SEnji Cooper public testing::TestWithParam<absl::string_view> { 108028f6c2f2SEnji Cooper // You can implement all the usual fixture class members here. 108128f6c2f2SEnji Cooper // To access the test parameter, call GetParam() from class 108228f6c2f2SEnji Cooper // TestWithParam<T>. 108328f6c2f2SEnji Cooper}; 108428f6c2f2SEnji Cooper 108528f6c2f2SEnji Cooper// Or, when you want to add parameters to a pre-existing fixture class: 108628f6c2f2SEnji Cooperclass BaseTest : public testing::Test { 108728f6c2f2SEnji Cooper ... 108828f6c2f2SEnji Cooper}; 108928f6c2f2SEnji Cooperclass BarTest : public BaseTest, 109028f6c2f2SEnji Cooper public testing::WithParamInterface<absl::string_view> { 109128f6c2f2SEnji Cooper ... 109228f6c2f2SEnji Cooper}; 109328f6c2f2SEnji Cooper``` 109428f6c2f2SEnji Cooper 109528f6c2f2SEnji CooperThen, use the `TEST_P` macro to define as many test patterns using this fixture 109628f6c2f2SEnji Cooperas you want. The `_P` suffix is for "parameterized" or "pattern", whichever you 109728f6c2f2SEnji Cooperprefer to think. 109828f6c2f2SEnji Cooper 109928f6c2f2SEnji Cooper```c++ 110028f6c2f2SEnji CooperTEST_P(FooTest, DoesBlah) { 110128f6c2f2SEnji Cooper // Inside a test, access the test parameter with the GetParam() method 110228f6c2f2SEnji Cooper // of the TestWithParam<T> class: 110328f6c2f2SEnji Cooper EXPECT_TRUE(foo.Blah(GetParam())); 110428f6c2f2SEnji Cooper ... 110528f6c2f2SEnji Cooper} 110628f6c2f2SEnji Cooper 110728f6c2f2SEnji CooperTEST_P(FooTest, HasBlahBlah) { 110828f6c2f2SEnji Cooper ... 110928f6c2f2SEnji Cooper} 111028f6c2f2SEnji Cooper``` 111128f6c2f2SEnji Cooper 111228f6c2f2SEnji CooperFinally, you can use the `INSTANTIATE_TEST_SUITE_P` macro to instantiate the 111328f6c2f2SEnji Coopertest suite with any set of parameters you want. GoogleTest defines a number of 111428f6c2f2SEnji Cooperfunctions for generating test parameters—see details at 111528f6c2f2SEnji Cooper[`INSTANTIATE_TEST_SUITE_P`](reference/testing.md#INSTANTIATE_TEST_SUITE_P) in 111628f6c2f2SEnji Cooperthe Testing Reference. 111728f6c2f2SEnji Cooper 111828f6c2f2SEnji CooperFor example, the following statement will instantiate tests from the `FooTest` 111928f6c2f2SEnji Coopertest suite each with parameter values `"meeny"`, `"miny"`, and `"moe"` using the 112028f6c2f2SEnji Cooper[`Values`](reference/testing.md#param-generators) parameter generator: 112128f6c2f2SEnji Cooper 112228f6c2f2SEnji Cooper```c++ 112328f6c2f2SEnji CooperINSTANTIATE_TEST_SUITE_P(MeenyMinyMoe, 112428f6c2f2SEnji Cooper FooTest, 112528f6c2f2SEnji Cooper testing::Values("meeny", "miny", "moe")); 112628f6c2f2SEnji Cooper``` 112728f6c2f2SEnji Cooper 112828f6c2f2SEnji Cooper{: .callout .note} 112928f6c2f2SEnji CooperNOTE: The code above must be placed at global or namespace scope, not at 113028f6c2f2SEnji Cooperfunction scope. 113128f6c2f2SEnji Cooper 113228f6c2f2SEnji CooperThe first argument to `INSTANTIATE_TEST_SUITE_P` is a unique name for the 113328f6c2f2SEnji Cooperinstantiation of the test suite. The next argument is the name of the test 113428f6c2f2SEnji Cooperpattern, and the last is the 113528f6c2f2SEnji Cooper[parameter generator](reference/testing.md#param-generators). 113628f6c2f2SEnji Cooper 113728f6c2f2SEnji CooperThe parameter generator expression is not evaluated until GoogleTest is 113828f6c2f2SEnji Cooperinitialized (via `InitGoogleTest()`). Any prior initialization done in the 113928f6c2f2SEnji Cooper`main` function will be accessible from the parameter generator, for example, 114028f6c2f2SEnji Cooperthe results of flag parsing. 114128f6c2f2SEnji Cooper 114228f6c2f2SEnji CooperYou can instantiate a test pattern more than once, so to distinguish different 114328f6c2f2SEnji Cooperinstances of the pattern, the instantiation name is added as a prefix to the 114428f6c2f2SEnji Cooperactual test suite name. Remember to pick unique prefixes for different 114528f6c2f2SEnji Cooperinstantiations. The tests from the instantiation above will have these names: 114628f6c2f2SEnji Cooper 114728f6c2f2SEnji Cooper* `MeenyMinyMoe/FooTest.DoesBlah/0` for `"meeny"` 114828f6c2f2SEnji Cooper* `MeenyMinyMoe/FooTest.DoesBlah/1` for `"miny"` 114928f6c2f2SEnji Cooper* `MeenyMinyMoe/FooTest.DoesBlah/2` for `"moe"` 115028f6c2f2SEnji Cooper* `MeenyMinyMoe/FooTest.HasBlahBlah/0` for `"meeny"` 115128f6c2f2SEnji Cooper* `MeenyMinyMoe/FooTest.HasBlahBlah/1` for `"miny"` 115228f6c2f2SEnji Cooper* `MeenyMinyMoe/FooTest.HasBlahBlah/2` for `"moe"` 115328f6c2f2SEnji Cooper 115428f6c2f2SEnji CooperYou can use these names in [`--gtest_filter`](#running-a-subset-of-the-tests). 115528f6c2f2SEnji Cooper 115628f6c2f2SEnji CooperThe following statement will instantiate all tests from `FooTest` again, each 115728f6c2f2SEnji Cooperwith parameter values `"cat"` and `"dog"` using the 115828f6c2f2SEnji Cooper[`ValuesIn`](reference/testing.md#param-generators) parameter generator: 115928f6c2f2SEnji Cooper 116028f6c2f2SEnji Cooper```c++ 116128f6c2f2SEnji Cooperconstexpr absl::string_view kPets[] = {"cat", "dog"}; 116228f6c2f2SEnji CooperINSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets)); 116328f6c2f2SEnji Cooper``` 116428f6c2f2SEnji Cooper 116528f6c2f2SEnji CooperThe tests from the instantiation above will have these names: 116628f6c2f2SEnji Cooper 116728f6c2f2SEnji Cooper* `Pets/FooTest.DoesBlah/0` for `"cat"` 116828f6c2f2SEnji Cooper* `Pets/FooTest.DoesBlah/1` for `"dog"` 116928f6c2f2SEnji Cooper* `Pets/FooTest.HasBlahBlah/0` for `"cat"` 117028f6c2f2SEnji Cooper* `Pets/FooTest.HasBlahBlah/1` for `"dog"` 117128f6c2f2SEnji Cooper 117228f6c2f2SEnji CooperPlease note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the 117328f6c2f2SEnji Coopergiven test suite, whether their definitions come before or *after* the 117428f6c2f2SEnji Cooper`INSTANTIATE_TEST_SUITE_P` statement. 117528f6c2f2SEnji Cooper 117628f6c2f2SEnji CooperAdditionally, by default, every `TEST_P` without a corresponding 117728f6c2f2SEnji Cooper`INSTANTIATE_TEST_SUITE_P` causes a failing test in test suite 117828f6c2f2SEnji Cooper`GoogleTestVerification`. If you have a test suite where that omission is not an 117928f6c2f2SEnji Coopererror, for example it is in a library that may be linked in for other reasons or 118028f6c2f2SEnji Cooperwhere the list of test cases is dynamic and may be empty, then this check can be 118128f6c2f2SEnji Coopersuppressed by tagging the test suite: 118228f6c2f2SEnji Cooper 118328f6c2f2SEnji Cooper```c++ 118428f6c2f2SEnji CooperGTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest); 118528f6c2f2SEnji Cooper``` 118628f6c2f2SEnji Cooper 118728f6c2f2SEnji CooperYou can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples. 118828f6c2f2SEnji Cooper 118928f6c2f2SEnji Cooper[sample7_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc "Parameterized Test example" 119028f6c2f2SEnji Cooper[sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters" 119128f6c2f2SEnji Cooper 119228f6c2f2SEnji Cooper### Creating Value-Parameterized Abstract Tests 119328f6c2f2SEnji Cooper 119428f6c2f2SEnji CooperIn the above, we define and instantiate `FooTest` in the *same* source file. 119528f6c2f2SEnji CooperSometimes you may want to define value-parameterized tests in a library and let 119628f6c2f2SEnji Cooperother people instantiate them later. This pattern is known as *abstract tests*. 119728f6c2f2SEnji CooperAs an example of its application, when you are designing an interface you can 119828f6c2f2SEnji Cooperwrite a standard suite of abstract tests (perhaps using a factory function as 119928f6c2f2SEnji Cooperthe test parameter) that all implementations of the interface are expected to 120028f6c2f2SEnji Cooperpass. When someone implements the interface, they can instantiate your suite to 120128f6c2f2SEnji Cooperget all the interface-conformance tests for free. 120228f6c2f2SEnji Cooper 120328f6c2f2SEnji CooperTo define abstract tests, you should organize your code like this: 120428f6c2f2SEnji Cooper 120528f6c2f2SEnji Cooper1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) 120628f6c2f2SEnji Cooper in a header file, say `foo_param_test.h`. Think of this as *declaring* your 120728f6c2f2SEnji Cooper abstract tests. 120828f6c2f2SEnji Cooper2. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes 120928f6c2f2SEnji Cooper `foo_param_test.h`. Think of this as *implementing* your abstract tests. 121028f6c2f2SEnji Cooper 121128f6c2f2SEnji CooperOnce they are defined, you can instantiate them by including `foo_param_test.h`, 121228f6c2f2SEnji Cooperinvoking `INSTANTIATE_TEST_SUITE_P()`, and depending on the library target that 121328f6c2f2SEnji Coopercontains `foo_param_test.cc`. You can instantiate the same abstract test suite 121428f6c2f2SEnji Coopermultiple times, possibly in different source files. 121528f6c2f2SEnji Cooper 121628f6c2f2SEnji Cooper### Specifying Names for Value-Parameterized Test Parameters 121728f6c2f2SEnji Cooper 121828f6c2f2SEnji CooperThe optional last argument to `INSTANTIATE_TEST_SUITE_P()` allows the user to 121928f6c2f2SEnji Cooperspecify a function or functor that generates custom test name suffixes based on 122028f6c2f2SEnji Cooperthe test parameters. The function should accept one argument of type 122128f6c2f2SEnji Cooper`testing::TestParamInfo<class ParamType>`, and return `std::string`. 122228f6c2f2SEnji Cooper 122328f6c2f2SEnji Cooper`testing::PrintToStringParamName` is a builtin test suffix generator that 122428f6c2f2SEnji Cooperreturns the value of `testing::PrintToString(GetParam())`. It does not work for 122528f6c2f2SEnji Cooper`std::string` or C strings. 122628f6c2f2SEnji Cooper 122728f6c2f2SEnji Cooper{: .callout .note} 122828f6c2f2SEnji CooperNOTE: test names must be non-empty, unique, and may only contain ASCII 122928f6c2f2SEnji Cooperalphanumeric characters. In particular, they 123028f6c2f2SEnji Cooper[should not contain underscores](faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore) 123128f6c2f2SEnji Cooper 123228f6c2f2SEnji Cooper```c++ 123328f6c2f2SEnji Cooperclass MyTestSuite : public testing::TestWithParam<int> {}; 123428f6c2f2SEnji Cooper 123528f6c2f2SEnji CooperTEST_P(MyTestSuite, MyTest) 123628f6c2f2SEnji Cooper{ 123728f6c2f2SEnji Cooper std::cout << "Example Test Param: " << GetParam() << std::endl; 123828f6c2f2SEnji Cooper} 123928f6c2f2SEnji Cooper 124028f6c2f2SEnji CooperINSTANTIATE_TEST_SUITE_P(MyGroup, MyTestSuite, testing::Range(0, 10), 124128f6c2f2SEnji Cooper testing::PrintToStringParamName()); 124228f6c2f2SEnji Cooper``` 124328f6c2f2SEnji Cooper 124428f6c2f2SEnji CooperProviding a custom functor allows for more control over test parameter name 124528f6c2f2SEnji Coopergeneration, especially for types where the automatic conversion does not 124628f6c2f2SEnji Coopergenerate helpful parameter names (e.g. strings as demonstrated above). The 124728f6c2f2SEnji Cooperfollowing example illustrates this for multiple parameters, an enumeration type 124828f6c2f2SEnji Cooperand a string, and also demonstrates how to combine generators. It uses a lambda 124928f6c2f2SEnji Cooperfor conciseness: 125028f6c2f2SEnji Cooper 125128f6c2f2SEnji Cooper```c++ 125228f6c2f2SEnji Cooperenum class MyType { MY_FOO = 0, MY_BAR = 1 }; 125328f6c2f2SEnji Cooper 125428f6c2f2SEnji Cooperclass MyTestSuite : public testing::TestWithParam<std::tuple<MyType, std::string>> { 125528f6c2f2SEnji Cooper}; 125628f6c2f2SEnji Cooper 125728f6c2f2SEnji CooperINSTANTIATE_TEST_SUITE_P( 125828f6c2f2SEnji Cooper MyGroup, MyTestSuite, 125928f6c2f2SEnji Cooper testing::Combine( 126028f6c2f2SEnji Cooper testing::Values(MyType::MY_FOO, MyType::MY_BAR), 126128f6c2f2SEnji Cooper testing::Values("A", "B")), 126228f6c2f2SEnji Cooper [](const testing::TestParamInfo<MyTestSuite::ParamType>& info) { 126328f6c2f2SEnji Cooper std::string name = absl::StrCat( 126428f6c2f2SEnji Cooper std::get<0>(info.param) == MyType::MY_FOO ? "Foo" : "Bar", 126528f6c2f2SEnji Cooper std::get<1>(info.param)); 126628f6c2f2SEnji Cooper absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_'); 126728f6c2f2SEnji Cooper return name; 126828f6c2f2SEnji Cooper }); 126928f6c2f2SEnji Cooper``` 127028f6c2f2SEnji Cooper 127128f6c2f2SEnji Cooper## Typed Tests 127228f6c2f2SEnji Cooper 127328f6c2f2SEnji CooperSuppose you have multiple implementations of the same interface and want to make 127428f6c2f2SEnji Coopersure that all of them satisfy some common requirements. Or, you may have defined 127528f6c2f2SEnji Cooperseveral types that are supposed to conform to the same "concept" and you want to 127628f6c2f2SEnji Cooperverify it. In both cases, you want the same test logic repeated for different 127728f6c2f2SEnji Coopertypes. 127828f6c2f2SEnji Cooper 127928f6c2f2SEnji CooperWhile you can write one `TEST` or `TEST_F` for each type you want to test (and 128028f6c2f2SEnji Cooperyou may even factor the test logic into a function template that you invoke from 128128f6c2f2SEnji Cooperthe `TEST`), it's tedious and doesn't scale: if you want `m` tests over `n` 128228f6c2f2SEnji Coopertypes, you'll end up writing `m*n` `TEST`s. 128328f6c2f2SEnji Cooper 128428f6c2f2SEnji Cooper*Typed tests* allow you to repeat the same test logic over a list of types. You 128528f6c2f2SEnji Cooperonly need to write the test logic once, although you must know the type list 128628f6c2f2SEnji Cooperwhen writing typed tests. Here's how you do it: 128728f6c2f2SEnji Cooper 128828f6c2f2SEnji CooperFirst, define a fixture class template. It should be parameterized by a type. 128928f6c2f2SEnji CooperRemember to derive it from `::testing::Test`: 129028f6c2f2SEnji Cooper 129128f6c2f2SEnji Cooper```c++ 129228f6c2f2SEnji Coopertemplate <typename T> 129328f6c2f2SEnji Cooperclass FooTest : public testing::Test { 129428f6c2f2SEnji Cooper public: 129528f6c2f2SEnji Cooper ... 129628f6c2f2SEnji Cooper using List = std::list<T>; 129728f6c2f2SEnji Cooper static T shared_; 129828f6c2f2SEnji Cooper T value_; 129928f6c2f2SEnji Cooper}; 130028f6c2f2SEnji Cooper``` 130128f6c2f2SEnji Cooper 130228f6c2f2SEnji CooperNext, associate a list of types with the test suite, which will be repeated for 130328f6c2f2SEnji Coopereach type in the list: 130428f6c2f2SEnji Cooper 130528f6c2f2SEnji Cooper```c++ 130628f6c2f2SEnji Cooperusing MyTypes = ::testing::Types<char, int, unsigned int>; 130728f6c2f2SEnji CooperTYPED_TEST_SUITE(FooTest, MyTypes); 130828f6c2f2SEnji Cooper``` 130928f6c2f2SEnji Cooper 131028f6c2f2SEnji CooperThe type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` 131128f6c2f2SEnji Coopermacro to parse correctly. Otherwise the compiler will think that each comma in 131228f6c2f2SEnji Cooperthe type list introduces a new macro argument. 131328f6c2f2SEnji Cooper 131428f6c2f2SEnji CooperThen, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this 131528f6c2f2SEnji Coopertest suite. You can repeat this as many times as you want: 131628f6c2f2SEnji Cooper 131728f6c2f2SEnji Cooper```c++ 131828f6c2f2SEnji CooperTYPED_TEST(FooTest, DoesBlah) { 131928f6c2f2SEnji Cooper // Inside a test, refer to the special name TypeParam to get the type 132028f6c2f2SEnji Cooper // parameter. Since we are inside a derived class template, C++ requires 132128f6c2f2SEnji Cooper // us to visit the members of FooTest via 'this'. 132228f6c2f2SEnji Cooper TypeParam n = this->value_; 132328f6c2f2SEnji Cooper 132428f6c2f2SEnji Cooper // To visit static members of the fixture, add the 'TestFixture::' 132528f6c2f2SEnji Cooper // prefix. 132628f6c2f2SEnji Cooper n += TestFixture::shared_; 132728f6c2f2SEnji Cooper 132828f6c2f2SEnji Cooper // To refer to typedefs in the fixture, add the 'typename TestFixture::' 132928f6c2f2SEnji Cooper // prefix. The 'typename' is required to satisfy the compiler. 133028f6c2f2SEnji Cooper typename TestFixture::List values; 133128f6c2f2SEnji Cooper 133228f6c2f2SEnji Cooper values.push_back(n); 133328f6c2f2SEnji Cooper ... 133428f6c2f2SEnji Cooper} 133528f6c2f2SEnji Cooper 133628f6c2f2SEnji CooperTYPED_TEST(FooTest, HasPropertyA) { ... } 133728f6c2f2SEnji Cooper``` 133828f6c2f2SEnji Cooper 133928f6c2f2SEnji CooperYou can see [sample6_unittest.cc] for a complete example. 134028f6c2f2SEnji Cooper 134128f6c2f2SEnji Cooper[sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example" 134228f6c2f2SEnji Cooper 134328f6c2f2SEnji Cooper## Type-Parameterized Tests 134428f6c2f2SEnji Cooper 134528f6c2f2SEnji Cooper*Type-parameterized tests* are like typed tests, except that they don't require 134628f6c2f2SEnji Cooperyou to know the list of types ahead of time. Instead, you can define the test 134728f6c2f2SEnji Cooperlogic first and instantiate it with different type lists later. You can even 134828f6c2f2SEnji Cooperinstantiate it more than once in the same program. 134928f6c2f2SEnji Cooper 135028f6c2f2SEnji CooperIf you are designing an interface or concept, you can define a suite of 135128f6c2f2SEnji Coopertype-parameterized tests to verify properties that any valid implementation of 135228f6c2f2SEnji Cooperthe interface/concept should have. Then, the author of each implementation can 135328f6c2f2SEnji Cooperjust instantiate the test suite with their type to verify that it conforms to 135428f6c2f2SEnji Cooperthe requirements, without having to write similar tests repeatedly. Here's an 135528f6c2f2SEnji Cooperexample: 135628f6c2f2SEnji Cooper 135728f6c2f2SEnji CooperFirst, define a fixture class template, as we did with typed tests: 135828f6c2f2SEnji Cooper 135928f6c2f2SEnji Cooper```c++ 136028f6c2f2SEnji Coopertemplate <typename T> 136128f6c2f2SEnji Cooperclass FooTest : public testing::Test { 136228f6c2f2SEnji Cooper void DoSomethingInteresting(); 136328f6c2f2SEnji Cooper ... 136428f6c2f2SEnji Cooper}; 136528f6c2f2SEnji Cooper``` 136628f6c2f2SEnji Cooper 136728f6c2f2SEnji CooperNext, declare that you will define a type-parameterized test suite: 136828f6c2f2SEnji Cooper 136928f6c2f2SEnji Cooper```c++ 137028f6c2f2SEnji CooperTYPED_TEST_SUITE_P(FooTest); 137128f6c2f2SEnji Cooper``` 137228f6c2f2SEnji Cooper 137328f6c2f2SEnji CooperThen, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat 137428f6c2f2SEnji Cooperthis as many times as you want: 137528f6c2f2SEnji Cooper 137628f6c2f2SEnji Cooper```c++ 137728f6c2f2SEnji CooperTYPED_TEST_P(FooTest, DoesBlah) { 137828f6c2f2SEnji Cooper // Inside a test, refer to TypeParam to get the type parameter. 137928f6c2f2SEnji Cooper TypeParam n = 0; 138028f6c2f2SEnji Cooper 138128f6c2f2SEnji Cooper // You will need to use `this` explicitly to refer to fixture members. 138228f6c2f2SEnji Cooper this->DoSomethingInteresting() 138328f6c2f2SEnji Cooper ... 138428f6c2f2SEnji Cooper} 138528f6c2f2SEnji Cooper 138628f6c2f2SEnji CooperTYPED_TEST_P(FooTest, HasPropertyA) { ... } 138728f6c2f2SEnji Cooper``` 138828f6c2f2SEnji Cooper 138928f6c2f2SEnji CooperNow the tricky part: you need to register all test patterns using the 139028f6c2f2SEnji Cooper`REGISTER_TYPED_TEST_SUITE_P` macro before you can instantiate them. The first 139128f6c2f2SEnji Cooperargument of the macro is the test suite name; the rest are the names of the 139228f6c2f2SEnji Coopertests in this test suite: 139328f6c2f2SEnji Cooper 139428f6c2f2SEnji Cooper```c++ 139528f6c2f2SEnji CooperREGISTER_TYPED_TEST_SUITE_P(FooTest, 139628f6c2f2SEnji Cooper DoesBlah, HasPropertyA); 139728f6c2f2SEnji Cooper``` 139828f6c2f2SEnji Cooper 139928f6c2f2SEnji CooperFinally, you are free to instantiate the pattern with the types you want. If you 140028f6c2f2SEnji Cooperput the above code in a header file, you can `#include` it in multiple C++ 140128f6c2f2SEnji Coopersource files and instantiate it multiple times. 140228f6c2f2SEnji Cooper 140328f6c2f2SEnji Cooper```c++ 140428f6c2f2SEnji Cooperusing MyTypes = ::testing::Types<char, int, unsigned int>; 140528f6c2f2SEnji CooperINSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); 140628f6c2f2SEnji Cooper``` 140728f6c2f2SEnji Cooper 140828f6c2f2SEnji CooperTo distinguish different instances of the pattern, the first argument to the 140928f6c2f2SEnji Cooper`INSTANTIATE_TYPED_TEST_SUITE_P` macro is a prefix that will be added to the 141028f6c2f2SEnji Cooperactual test suite name. Remember to pick unique prefixes for different 141128f6c2f2SEnji Cooperinstances. 141228f6c2f2SEnji Cooper 141328f6c2f2SEnji CooperIn the special case where the type list contains only one type, you can write 141428f6c2f2SEnji Cooperthat type directly without `::testing::Types<...>`, like this: 141528f6c2f2SEnji Cooper 141628f6c2f2SEnji Cooper```c++ 141728f6c2f2SEnji CooperINSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); 141828f6c2f2SEnji Cooper``` 141928f6c2f2SEnji Cooper 142028f6c2f2SEnji CooperYou can see [sample6_unittest.cc] for a complete example. 142128f6c2f2SEnji Cooper 142228f6c2f2SEnji Cooper## Testing Private Code 142328f6c2f2SEnji Cooper 142428f6c2f2SEnji CooperIf you change your software's internal implementation, your tests should not 142528f6c2f2SEnji Cooperbreak as long as the change is not observable by users. Therefore, **per the 142628f6c2f2SEnji Cooperblack-box testing principle, most of the time you should test your code through 142728f6c2f2SEnji Cooperits public interfaces.** 142828f6c2f2SEnji Cooper 142928f6c2f2SEnji Cooper**If you still find yourself needing to test internal implementation code, 143028f6c2f2SEnji Cooperconsider if there's a better design.** The desire to test internal 143128f6c2f2SEnji Cooperimplementation is often a sign that the class is doing too much. Consider 143228f6c2f2SEnji Cooperextracting an implementation class, and testing it. Then use that implementation 143328f6c2f2SEnji Cooperclass in the original class. 143428f6c2f2SEnji Cooper 143528f6c2f2SEnji CooperIf you absolutely have to test non-public interface code though, you can. There 143628f6c2f2SEnji Cooperare two cases to consider: 143728f6c2f2SEnji Cooper 143828f6c2f2SEnji Cooper* Static functions ( *not* the same as static member functions!) or unnamed 143928f6c2f2SEnji Cooper namespaces, and 144028f6c2f2SEnji Cooper* Private or protected class members 144128f6c2f2SEnji Cooper 144228f6c2f2SEnji CooperTo test them, we use the following special techniques: 144328f6c2f2SEnji Cooper 144428f6c2f2SEnji Cooper* Both static functions and definitions/declarations in an unnamed namespace 144528f6c2f2SEnji Cooper are only visible within the same translation unit. To test them, you can 144628f6c2f2SEnji Cooper `#include` the entire `.cc` file being tested in your `*_test.cc` file. 144728f6c2f2SEnji Cooper (#including `.cc` files is not a good way to reuse code - you should not do 144828f6c2f2SEnji Cooper this in production code!) 144928f6c2f2SEnji Cooper 145028f6c2f2SEnji Cooper However, a better approach is to move the private code into the 145128f6c2f2SEnji Cooper `foo::internal` namespace, where `foo` is the namespace your project 145228f6c2f2SEnji Cooper normally uses, and put the private declarations in a `*-internal.h` file. 145328f6c2f2SEnji Cooper Your production `.cc` files and your tests are allowed to include this 145428f6c2f2SEnji Cooper internal header, but your clients are not. This way, you can fully test your 145528f6c2f2SEnji Cooper internal implementation without leaking it to your clients. 145628f6c2f2SEnji Cooper 145728f6c2f2SEnji Cooper* Private class members are only accessible from within the class or by 145828f6c2f2SEnji Cooper friends. To access a class' private members, you can declare your test 145928f6c2f2SEnji Cooper fixture as a friend to the class and define accessors in your fixture. Tests 146028f6c2f2SEnji Cooper using the fixture can then access the private members of your production 146128f6c2f2SEnji Cooper class via the accessors in the fixture. Note that even though your fixture 146228f6c2f2SEnji Cooper is a friend to your production class, your tests are not automatically 146328f6c2f2SEnji Cooper friends to it, as they are technically defined in sub-classes of the 146428f6c2f2SEnji Cooper fixture. 146528f6c2f2SEnji Cooper 146628f6c2f2SEnji Cooper Another way to test private members is to refactor them into an 146728f6c2f2SEnji Cooper implementation class, which is then declared in a `*-internal.h` file. Your 146828f6c2f2SEnji Cooper clients aren't allowed to include this header but your tests can. Such is 146928f6c2f2SEnji Cooper called the 147028f6c2f2SEnji Cooper [Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/) 147128f6c2f2SEnji Cooper (Private Implementation) idiom. 147228f6c2f2SEnji Cooper 147328f6c2f2SEnji Cooper Or, you can declare an individual test as a friend of your class by adding 147428f6c2f2SEnji Cooper this line in the class body: 147528f6c2f2SEnji Cooper 147628f6c2f2SEnji Cooper ```c++ 147728f6c2f2SEnji Cooper FRIEND_TEST(TestSuiteName, TestName); 147828f6c2f2SEnji Cooper ``` 147928f6c2f2SEnji Cooper 148028f6c2f2SEnji Cooper For example, 148128f6c2f2SEnji Cooper 148228f6c2f2SEnji Cooper ```c++ 148328f6c2f2SEnji Cooper // foo.h 148428f6c2f2SEnji Cooper class Foo { 148528f6c2f2SEnji Cooper ... 148628f6c2f2SEnji Cooper private: 148728f6c2f2SEnji Cooper FRIEND_TEST(FooTest, BarReturnsZeroOnNull); 148828f6c2f2SEnji Cooper 148928f6c2f2SEnji Cooper int Bar(void* x); 149028f6c2f2SEnji Cooper }; 149128f6c2f2SEnji Cooper 149228f6c2f2SEnji Cooper // foo_test.cc 149328f6c2f2SEnji Cooper ... 149428f6c2f2SEnji Cooper TEST(FooTest, BarReturnsZeroOnNull) { 149528f6c2f2SEnji Cooper Foo foo; 149628f6c2f2SEnji Cooper EXPECT_EQ(foo.Bar(NULL), 0); // Uses Foo's private member Bar(). 149728f6c2f2SEnji Cooper } 149828f6c2f2SEnji Cooper ``` 149928f6c2f2SEnji Cooper 150028f6c2f2SEnji Cooper Pay special attention when your class is defined in a namespace. If you want 150128f6c2f2SEnji Cooper your test fixtures and tests to be friends of your class, then they must be 150228f6c2f2SEnji Cooper defined in the exact same namespace (no anonymous or inline namespaces). 150328f6c2f2SEnji Cooper 150428f6c2f2SEnji Cooper For example, if the code to be tested looks like: 150528f6c2f2SEnji Cooper 150628f6c2f2SEnji Cooper ```c++ 150728f6c2f2SEnji Cooper namespace my_namespace { 150828f6c2f2SEnji Cooper 150928f6c2f2SEnji Cooper class Foo { 151028f6c2f2SEnji Cooper friend class FooTest; 151128f6c2f2SEnji Cooper FRIEND_TEST(FooTest, Bar); 151228f6c2f2SEnji Cooper FRIEND_TEST(FooTest, Baz); 151328f6c2f2SEnji Cooper ... definition of the class Foo ... 151428f6c2f2SEnji Cooper }; 151528f6c2f2SEnji Cooper 151628f6c2f2SEnji Cooper } // namespace my_namespace 151728f6c2f2SEnji Cooper ``` 151828f6c2f2SEnji Cooper 151928f6c2f2SEnji Cooper Your test code should be something like: 152028f6c2f2SEnji Cooper 152128f6c2f2SEnji Cooper ```c++ 152228f6c2f2SEnji Cooper namespace my_namespace { 152328f6c2f2SEnji Cooper 152428f6c2f2SEnji Cooper class FooTest : public testing::Test { 152528f6c2f2SEnji Cooper protected: 152628f6c2f2SEnji Cooper ... 152728f6c2f2SEnji Cooper }; 152828f6c2f2SEnji Cooper 152928f6c2f2SEnji Cooper TEST_F(FooTest, Bar) { ... } 153028f6c2f2SEnji Cooper TEST_F(FooTest, Baz) { ... } 153128f6c2f2SEnji Cooper 153228f6c2f2SEnji Cooper } // namespace my_namespace 153328f6c2f2SEnji Cooper ``` 153428f6c2f2SEnji Cooper 153528f6c2f2SEnji Cooper## "Catching" Failures 153628f6c2f2SEnji Cooper 153728f6c2f2SEnji CooperIf you are building a testing utility on top of GoogleTest, you'll want to test 153828f6c2f2SEnji Cooperyour utility. What framework would you use to test it? GoogleTest, of course. 153928f6c2f2SEnji Cooper 154028f6c2f2SEnji CooperThe challenge is to verify that your testing utility reports failures correctly. 154128f6c2f2SEnji CooperIn frameworks that report a failure by throwing an exception, you could catch 154228f6c2f2SEnji Cooperthe exception and assert on it. But GoogleTest doesn't use exceptions, so how do 154328f6c2f2SEnji Cooperwe test that a piece of code generates an expected failure? 154428f6c2f2SEnji Cooper 154528f6c2f2SEnji Cooper`"gtest/gtest-spi.h"` contains some constructs to do this. 154628f6c2f2SEnji CooperAfter #including this header, you can use 154728f6c2f2SEnji Cooper 154828f6c2f2SEnji Cooper```c++ 154928f6c2f2SEnji Cooper EXPECT_FATAL_FAILURE(statement, substring); 155028f6c2f2SEnji Cooper``` 155128f6c2f2SEnji Cooper 155228f6c2f2SEnji Cooperto assert that `statement` generates a fatal (e.g. `ASSERT_*`) failure in the 155328f6c2f2SEnji Coopercurrent thread whose message contains the given `substring`, or use 155428f6c2f2SEnji Cooper 155528f6c2f2SEnji Cooper```c++ 155628f6c2f2SEnji Cooper EXPECT_NONFATAL_FAILURE(statement, substring); 155728f6c2f2SEnji Cooper``` 155828f6c2f2SEnji Cooper 155928f6c2f2SEnji Cooperif you are expecting a non-fatal (e.g. `EXPECT_*`) failure. 156028f6c2f2SEnji Cooper 156128f6c2f2SEnji CooperOnly failures in the current thread are checked to determine the result of this 156228f6c2f2SEnji Coopertype of expectations. If `statement` creates new threads, failures in these 156328f6c2f2SEnji Cooperthreads are also ignored. If you want to catch failures in other threads as 156428f6c2f2SEnji Cooperwell, use one of the following macros instead: 156528f6c2f2SEnji Cooper 156628f6c2f2SEnji Cooper```c++ 156728f6c2f2SEnji Cooper EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substring); 156828f6c2f2SEnji Cooper EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring); 156928f6c2f2SEnji Cooper``` 157028f6c2f2SEnji Cooper 157128f6c2f2SEnji Cooper{: .callout .note} 157228f6c2f2SEnji CooperNOTE: Assertions from multiple threads are currently not supported on Windows. 157328f6c2f2SEnji Cooper 157428f6c2f2SEnji CooperFor technical reasons, there are some caveats: 157528f6c2f2SEnji Cooper 157628f6c2f2SEnji Cooper1. You cannot stream a failure message to either macro. 157728f6c2f2SEnji Cooper 157828f6c2f2SEnji Cooper2. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot reference 157928f6c2f2SEnji Cooper local non-static variables or non-static members of `this` object. 158028f6c2f2SEnji Cooper 158128f6c2f2SEnji Cooper3. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot return a 158228f6c2f2SEnji Cooper value. 158328f6c2f2SEnji Cooper 158428f6c2f2SEnji Cooper## Registering tests programmatically 158528f6c2f2SEnji Cooper 158628f6c2f2SEnji CooperThe `TEST` macros handle the vast majority of all use cases, but there are few 158728f6c2f2SEnji Cooperwhere runtime registration logic is required. For those cases, the framework 158828f6c2f2SEnji Cooperprovides the `::testing::RegisterTest` that allows callers to register arbitrary 158928f6c2f2SEnji Coopertests dynamically. 159028f6c2f2SEnji Cooper 159128f6c2f2SEnji CooperThis is an advanced API only to be used when the `TEST` macros are insufficient. 159228f6c2f2SEnji CooperThe macros should be preferred when possible, as they avoid most of the 159328f6c2f2SEnji Coopercomplexity of calling this function. 159428f6c2f2SEnji Cooper 159528f6c2f2SEnji CooperIt provides the following signature: 159628f6c2f2SEnji Cooper 159728f6c2f2SEnji Cooper```c++ 159828f6c2f2SEnji Coopertemplate <typename Factory> 159928f6c2f2SEnji CooperTestInfo* RegisterTest(const char* test_suite_name, const char* test_name, 160028f6c2f2SEnji Cooper const char* type_param, const char* value_param, 160128f6c2f2SEnji Cooper const char* file, int line, Factory factory); 160228f6c2f2SEnji Cooper``` 160328f6c2f2SEnji Cooper 160428f6c2f2SEnji CooperThe `factory` argument is a factory callable (move-constructible) object or 160528f6c2f2SEnji Cooperfunction pointer that creates a new instance of the Test object. It handles 160628f6c2f2SEnji Cooperownership to the caller. The signature of the callable is `Fixture*()`, where 160728f6c2f2SEnji Cooper`Fixture` is the test fixture class for the test. All tests registered with the 160828f6c2f2SEnji Coopersame `test_suite_name` must return the same fixture type. This is checked at 160928f6c2f2SEnji Cooperruntime. 161028f6c2f2SEnji Cooper 161128f6c2f2SEnji CooperThe framework will infer the fixture class from the factory and will call the 161228f6c2f2SEnji Cooper`SetUpTestSuite` and `TearDownTestSuite` for it. 161328f6c2f2SEnji Cooper 161428f6c2f2SEnji CooperMust be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is 161528f6c2f2SEnji Cooperundefined. 161628f6c2f2SEnji Cooper 161728f6c2f2SEnji CooperUse case example: 161828f6c2f2SEnji Cooper 161928f6c2f2SEnji Cooper```c++ 162028f6c2f2SEnji Cooperclass MyFixture : public testing::Test { 162128f6c2f2SEnji Cooper public: 162228f6c2f2SEnji Cooper // All of these optional, just like in regular macro usage. 162328f6c2f2SEnji Cooper static void SetUpTestSuite() { ... } 162428f6c2f2SEnji Cooper static void TearDownTestSuite() { ... } 162528f6c2f2SEnji Cooper void SetUp() override { ... } 162628f6c2f2SEnji Cooper void TearDown() override { ... } 162728f6c2f2SEnji Cooper}; 162828f6c2f2SEnji Cooper 162928f6c2f2SEnji Cooperclass MyTest : public MyFixture { 163028f6c2f2SEnji Cooper public: 163128f6c2f2SEnji Cooper explicit MyTest(int data) : data_(data) {} 163228f6c2f2SEnji Cooper void TestBody() override { ... } 163328f6c2f2SEnji Cooper 163428f6c2f2SEnji Cooper private: 163528f6c2f2SEnji Cooper int data_; 163628f6c2f2SEnji Cooper}; 163728f6c2f2SEnji Cooper 163828f6c2f2SEnji Coopervoid RegisterMyTests(const std::vector<int>& values) { 163928f6c2f2SEnji Cooper for (int v : values) { 164028f6c2f2SEnji Cooper testing::RegisterTest( 164128f6c2f2SEnji Cooper "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr, 164228f6c2f2SEnji Cooper std::to_string(v).c_str(), 164328f6c2f2SEnji Cooper __FILE__, __LINE__, 164428f6c2f2SEnji Cooper // Important to use the fixture type as the return type here. 164528f6c2f2SEnji Cooper [=]() -> MyFixture* { return new MyTest(v); }); 164628f6c2f2SEnji Cooper } 164728f6c2f2SEnji Cooper} 164828f6c2f2SEnji Cooper... 164928f6c2f2SEnji Cooperint main(int argc, char** argv) { 165028f6c2f2SEnji Cooper testing::InitGoogleTest(&argc, argv); 165128f6c2f2SEnji Cooper std::vector<int> values_to_test = LoadValuesFromConfig(); 165228f6c2f2SEnji Cooper RegisterMyTests(values_to_test); 165328f6c2f2SEnji Cooper ... 165428f6c2f2SEnji Cooper return RUN_ALL_TESTS(); 165528f6c2f2SEnji Cooper} 165628f6c2f2SEnji Cooper``` 165728f6c2f2SEnji Cooper 165828f6c2f2SEnji Cooper## Getting the Current Test's Name 165928f6c2f2SEnji Cooper 166028f6c2f2SEnji CooperSometimes a function may need to know the name of the currently running test. 166128f6c2f2SEnji CooperFor example, you may be using the `SetUp()` method of your test fixture to set 166228f6c2f2SEnji Cooperthe golden file name based on which test is running. The 166328f6c2f2SEnji Cooper[`TestInfo`](reference/testing.md#TestInfo) class has this information. 166428f6c2f2SEnji Cooper 166528f6c2f2SEnji CooperTo obtain a `TestInfo` object for the currently running test, call 166628f6c2f2SEnji Cooper`current_test_info()` on the [`UnitTest`](reference/testing.md#UnitTest) 166728f6c2f2SEnji Coopersingleton object: 166828f6c2f2SEnji Cooper 166928f6c2f2SEnji Cooper```c++ 167028f6c2f2SEnji Cooper // Gets information about the currently running test. 167128f6c2f2SEnji Cooper // Do NOT delete the returned object - it's managed by the UnitTest class. 167228f6c2f2SEnji Cooper const testing::TestInfo* const test_info = 167328f6c2f2SEnji Cooper testing::UnitTest::GetInstance()->current_test_info(); 167428f6c2f2SEnji Cooper 167528f6c2f2SEnji Cooper printf("We are in test %s of test suite %s.\n", 167628f6c2f2SEnji Cooper test_info->name(), 167728f6c2f2SEnji Cooper test_info->test_suite_name()); 167828f6c2f2SEnji Cooper``` 167928f6c2f2SEnji Cooper 168028f6c2f2SEnji Cooper`current_test_info()` returns a null pointer if no test is running. In 168128f6c2f2SEnji Cooperparticular, you cannot find the test suite name in `SetUpTestSuite()`, 168228f6c2f2SEnji Cooper`TearDownTestSuite()` (where you know the test suite name implicitly), or 168328f6c2f2SEnji Cooperfunctions called from them. 168428f6c2f2SEnji Cooper 168528f6c2f2SEnji Cooper## Extending GoogleTest by Handling Test Events 168628f6c2f2SEnji Cooper 168728f6c2f2SEnji CooperGoogleTest provides an **event listener API** to let you receive notifications 168828f6c2f2SEnji Cooperabout the progress of a test program and test failures. The events you can 168928f6c2f2SEnji Cooperlisten to include the start and end of the test program, a test suite, or a test 169028f6c2f2SEnji Coopermethod, among others. You may use this API to augment or replace the standard 169128f6c2f2SEnji Cooperconsole output, replace the XML output, or provide a completely different form 169228f6c2f2SEnji Cooperof output, such as a GUI or a database. You can also use test events as 169328f6c2f2SEnji Coopercheckpoints to implement a resource leak checker, for example. 169428f6c2f2SEnji Cooper 169528f6c2f2SEnji Cooper### Defining Event Listeners 169628f6c2f2SEnji Cooper 169728f6c2f2SEnji CooperTo define a event listener, you subclass either 169828f6c2f2SEnji Cooper[`testing::TestEventListener`](reference/testing.md#TestEventListener) or 169928f6c2f2SEnji Cooper[`testing::EmptyTestEventListener`](reference/testing.md#EmptyTestEventListener) 170028f6c2f2SEnji CooperThe former is an (abstract) interface, where *each pure virtual method can be 170128f6c2f2SEnji Cooperoverridden to handle a test event* (For example, when a test starts, the 170228f6c2f2SEnji Cooper`OnTestStart()` method will be called.). The latter provides an empty 170328f6c2f2SEnji Cooperimplementation of all methods in the interface, such that a subclass only needs 170428f6c2f2SEnji Cooperto override the methods it cares about. 170528f6c2f2SEnji Cooper 170628f6c2f2SEnji CooperWhen an event is fired, its context is passed to the handler function as an 170728f6c2f2SEnji Cooperargument. The following argument types are used: 170828f6c2f2SEnji Cooper 170928f6c2f2SEnji Cooper* UnitTest reflects the state of the entire test program, 171028f6c2f2SEnji Cooper* TestSuite has information about a test suite, which can contain one or more 171128f6c2f2SEnji Cooper tests, 171228f6c2f2SEnji Cooper* TestInfo contains the state of a test, and 171328f6c2f2SEnji Cooper* TestPartResult represents the result of a test assertion. 171428f6c2f2SEnji Cooper 171528f6c2f2SEnji CooperAn event handler function can examine the argument it receives to find out 171628f6c2f2SEnji Cooperinteresting information about the event and the test program's state. 171728f6c2f2SEnji Cooper 171828f6c2f2SEnji CooperHere's an example: 171928f6c2f2SEnji Cooper 172028f6c2f2SEnji Cooper```c++ 172128f6c2f2SEnji Cooper class MinimalistPrinter : public testing::EmptyTestEventListener { 172228f6c2f2SEnji Cooper // Called before a test starts. 172328f6c2f2SEnji Cooper void OnTestStart(const testing::TestInfo& test_info) override { 172428f6c2f2SEnji Cooper printf("*** Test %s.%s starting.\n", 172528f6c2f2SEnji Cooper test_info.test_suite_name(), test_info.name()); 172628f6c2f2SEnji Cooper } 172728f6c2f2SEnji Cooper 172828f6c2f2SEnji Cooper // Called after a failed assertion or a SUCCESS(). 172928f6c2f2SEnji Cooper void OnTestPartResult(const testing::TestPartResult& test_part_result) override { 173028f6c2f2SEnji Cooper printf("%s in %s:%d\n%s\n", 173128f6c2f2SEnji Cooper test_part_result.failed() ? "*** Failure" : "Success", 173228f6c2f2SEnji Cooper test_part_result.file_name(), 173328f6c2f2SEnji Cooper test_part_result.line_number(), 173428f6c2f2SEnji Cooper test_part_result.summary()); 173528f6c2f2SEnji Cooper } 173628f6c2f2SEnji Cooper 173728f6c2f2SEnji Cooper // Called after a test ends. 173828f6c2f2SEnji Cooper void OnTestEnd(const testing::TestInfo& test_info) override { 173928f6c2f2SEnji Cooper printf("*** Test %s.%s ending.\n", 174028f6c2f2SEnji Cooper test_info.test_suite_name(), test_info.name()); 174128f6c2f2SEnji Cooper } 174228f6c2f2SEnji Cooper }; 174328f6c2f2SEnji Cooper``` 174428f6c2f2SEnji Cooper 174528f6c2f2SEnji Cooper### Using Event Listeners 174628f6c2f2SEnji Cooper 174728f6c2f2SEnji CooperTo use the event listener you have defined, add an instance of it to the 174828f6c2f2SEnji CooperGoogleTest event listener list (represented by class 174928f6c2f2SEnji Cooper[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s" 175028f6c2f2SEnji Cooperat the end of the name) in your `main()` function, before calling 175128f6c2f2SEnji Cooper`RUN_ALL_TESTS()`: 175228f6c2f2SEnji Cooper 175328f6c2f2SEnji Cooper```c++ 175428f6c2f2SEnji Cooperint main(int argc, char** argv) { 175528f6c2f2SEnji Cooper testing::InitGoogleTest(&argc, argv); 175628f6c2f2SEnji Cooper // Gets hold of the event listener list. 175728f6c2f2SEnji Cooper testing::TestEventListeners& listeners = 175828f6c2f2SEnji Cooper testing::UnitTest::GetInstance()->listeners(); 175928f6c2f2SEnji Cooper // Adds a listener to the end. GoogleTest takes the ownership. 176028f6c2f2SEnji Cooper listeners.Append(new MinimalistPrinter); 176128f6c2f2SEnji Cooper return RUN_ALL_TESTS(); 176228f6c2f2SEnji Cooper} 176328f6c2f2SEnji Cooper``` 176428f6c2f2SEnji Cooper 176528f6c2f2SEnji CooperThere's only one problem: the default test result printer is still in effect, so 176628f6c2f2SEnji Cooperits output will mingle with the output from your minimalist printer. To suppress 176728f6c2f2SEnji Cooperthe default printer, just release it from the event listener list and delete it. 176828f6c2f2SEnji CooperYou can do so by adding one line: 176928f6c2f2SEnji Cooper 177028f6c2f2SEnji Cooper```c++ 177128f6c2f2SEnji Cooper ... 177228f6c2f2SEnji Cooper delete listeners.Release(listeners.default_result_printer()); 177328f6c2f2SEnji Cooper listeners.Append(new MinimalistPrinter); 177428f6c2f2SEnji Cooper return RUN_ALL_TESTS(); 177528f6c2f2SEnji Cooper``` 177628f6c2f2SEnji Cooper 177728f6c2f2SEnji CooperNow, sit back and enjoy a completely different output from your tests. For more 177828f6c2f2SEnji Cooperdetails, see [sample9_unittest.cc]. 177928f6c2f2SEnji Cooper 178028f6c2f2SEnji Cooper[sample9_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc "Event listener example" 178128f6c2f2SEnji Cooper 178228f6c2f2SEnji CooperYou may append more than one listener to the list. When an `On*Start()` or 178328f6c2f2SEnji Cooper`OnTestPartResult()` event is fired, the listeners will receive it in the order 178428f6c2f2SEnji Cooperthey appear in the list (since new listeners are added to the end of the list, 178528f6c2f2SEnji Cooperthe default text printer and the default XML generator will receive the event 178628f6c2f2SEnji Cooperfirst). An `On*End()` event will be received by the listeners in the *reverse* 178728f6c2f2SEnji Cooperorder. This allows output by listeners added later to be framed by output from 178828f6c2f2SEnji Cooperlisteners added earlier. 178928f6c2f2SEnji Cooper 179028f6c2f2SEnji Cooper### Generating Failures in Listeners 179128f6c2f2SEnji Cooper 179228f6c2f2SEnji CooperYou may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, `FAIL()`, etc) 179328f6c2f2SEnji Cooperwhen processing an event. There are some restrictions: 179428f6c2f2SEnji Cooper 179528f6c2f2SEnji Cooper1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will 179628f6c2f2SEnji Cooper cause `OnTestPartResult()` to be called recursively). 179728f6c2f2SEnji Cooper2. A listener that handles `OnTestPartResult()` is not allowed to generate any 179828f6c2f2SEnji Cooper failure. 179928f6c2f2SEnji Cooper 180028f6c2f2SEnji CooperWhen you add listeners to the listener list, you should put listeners that 180128f6c2f2SEnji Cooperhandle `OnTestPartResult()` *before* listeners that can generate failures. This 180228f6c2f2SEnji Cooperensures that failures generated by the latter are attributed to the right test 180328f6c2f2SEnji Cooperby the former. 180428f6c2f2SEnji Cooper 180528f6c2f2SEnji CooperSee [sample10_unittest.cc] for an example of a failure-raising listener. 180628f6c2f2SEnji Cooper 180728f6c2f2SEnji Cooper[sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example" 180828f6c2f2SEnji Cooper 180928f6c2f2SEnji Cooper## Running Test Programs: Advanced Options 181028f6c2f2SEnji Cooper 181128f6c2f2SEnji CooperGoogleTest test programs are ordinary executables. Once built, you can run them 181228f6c2f2SEnji Cooperdirectly and affect their behavior via the following environment variables 181328f6c2f2SEnji Cooperand/or command line flags. For the flags to work, your programs must call 181428f6c2f2SEnji Cooper`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. 181528f6c2f2SEnji Cooper 181628f6c2f2SEnji CooperTo see a list of supported flags and their usage, please run your test program 1817*5ca8c28cSEnji Cooperwith the `--help` flag. 181828f6c2f2SEnji Cooper 181928f6c2f2SEnji CooperIf an option is specified both by an environment variable and by a flag, the 182028f6c2f2SEnji Cooperlatter takes precedence. 182128f6c2f2SEnji Cooper 182228f6c2f2SEnji Cooper### Selecting Tests 182328f6c2f2SEnji Cooper 182428f6c2f2SEnji Cooper#### Listing Test Names 182528f6c2f2SEnji Cooper 182628f6c2f2SEnji CooperSometimes it is necessary to list the available tests in a program before 182728f6c2f2SEnji Cooperrunning them so that a filter may be applied if needed. Including the flag 182828f6c2f2SEnji Cooper`--gtest_list_tests` overrides all other flags and lists tests in the following 182928f6c2f2SEnji Cooperformat: 183028f6c2f2SEnji Cooper 183128f6c2f2SEnji Cooper```none 183228f6c2f2SEnji CooperTestSuite1. 183328f6c2f2SEnji Cooper TestName1 183428f6c2f2SEnji Cooper TestName2 183528f6c2f2SEnji CooperTestSuite2. 183628f6c2f2SEnji Cooper TestName 183728f6c2f2SEnji Cooper``` 183828f6c2f2SEnji Cooper 183928f6c2f2SEnji CooperNone of the tests listed are actually run if the flag is provided. There is no 184028f6c2f2SEnji Coopercorresponding environment variable for this flag. 184128f6c2f2SEnji Cooper 184228f6c2f2SEnji Cooper#### Running a Subset of the Tests 184328f6c2f2SEnji Cooper 184428f6c2f2SEnji CooperBy default, a GoogleTest program runs all tests the user has defined. Sometimes, 184528f6c2f2SEnji Cooperyou want to run only a subset of the tests (e.g. for debugging or quickly 184628f6c2f2SEnji Cooperverifying a change). If you set the `GTEST_FILTER` environment variable or the 184728f6c2f2SEnji Cooper`--gtest_filter` flag to a filter string, GoogleTest will only run the tests 184828f6c2f2SEnji Cooperwhose full names (in the form of `TestSuiteName.TestName`) match the filter. 184928f6c2f2SEnji Cooper 185028f6c2f2SEnji CooperThe format of a filter is a '`:`'-separated list of wildcard patterns (called 185128f6c2f2SEnji Cooperthe *positive patterns*) optionally followed by a '`-`' and another 185228f6c2f2SEnji Cooper'`:`'-separated pattern list (called the *negative patterns*). A test matches 185328f6c2f2SEnji Cooperthe filter if and only if it matches any of the positive patterns but does not 185428f6c2f2SEnji Coopermatch any of the negative patterns. 185528f6c2f2SEnji Cooper 185628f6c2f2SEnji CooperA pattern may contain `'*'` (matches any string) or `'?'` (matches any single 185728f6c2f2SEnji Coopercharacter). For convenience, the filter `'*-NegativePatterns'` can be also 185828f6c2f2SEnji Cooperwritten as `'-NegativePatterns'`. 185928f6c2f2SEnji Cooper 186028f6c2f2SEnji CooperFor example: 186128f6c2f2SEnji Cooper 186228f6c2f2SEnji Cooper* `./foo_test` Has no flag, and thus runs all its tests. 186328f6c2f2SEnji Cooper* `./foo_test --gtest_filter=*` Also runs everything, due to the single 186428f6c2f2SEnji Cooper match-everything `*` value. 186528f6c2f2SEnji Cooper* `./foo_test --gtest_filter=FooTest.*` Runs everything in test suite 186628f6c2f2SEnji Cooper `FooTest` . 186728f6c2f2SEnji Cooper* `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full 186828f6c2f2SEnji Cooper name contains either `"Null"` or `"Constructor"` . 186928f6c2f2SEnji Cooper* `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. 187028f6c2f2SEnji Cooper* `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test 187128f6c2f2SEnji Cooper suite `FooTest` except `FooTest.Bar`. 187228f6c2f2SEnji Cooper* `./foo_test --gtest_filter=FooTest.*:BarTest.*-FooTest.Bar:BarTest.Foo` Runs 187328f6c2f2SEnji Cooper everything in test suite `FooTest` except `FooTest.Bar` and everything in 187428f6c2f2SEnji Cooper test suite `BarTest` except `BarTest.Foo`. 187528f6c2f2SEnji Cooper 187628f6c2f2SEnji Cooper#### Stop test execution upon first failure 187728f6c2f2SEnji Cooper 187828f6c2f2SEnji CooperBy default, a GoogleTest program runs all tests the user has defined. In some 187928f6c2f2SEnji Coopercases (e.g. iterative test development & execution) it may be desirable stop 188028f6c2f2SEnji Coopertest execution upon first failure (trading improved latency for completeness). 188128f6c2f2SEnji CooperIf `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set, 188228f6c2f2SEnji Cooperthe test runner will stop execution as soon as the first test failure is found. 188328f6c2f2SEnji Cooper 188428f6c2f2SEnji Cooper#### Temporarily Disabling Tests 188528f6c2f2SEnji Cooper 188628f6c2f2SEnji CooperIf you have a broken test that you cannot fix right away, you can add the 188728f6c2f2SEnji Cooper`DISABLED_` prefix to its name. This will exclude it from execution. This is 188828f6c2f2SEnji Cooperbetter than commenting out the code or using `#if 0`, as disabled tests are 188928f6c2f2SEnji Cooperstill compiled (and thus won't rot). 189028f6c2f2SEnji Cooper 189128f6c2f2SEnji CooperIf you need to disable all tests in a test suite, you can either add `DISABLED_` 189228f6c2f2SEnji Cooperto the front of the name of each test, or alternatively add it to the front of 189328f6c2f2SEnji Cooperthe test suite name. 189428f6c2f2SEnji Cooper 189528f6c2f2SEnji CooperFor example, the following tests won't be run by GoogleTest, even though they 189628f6c2f2SEnji Cooperwill still be compiled: 189728f6c2f2SEnji Cooper 189828f6c2f2SEnji Cooper```c++ 189928f6c2f2SEnji Cooper// Tests that Foo does Abc. 190028f6c2f2SEnji CooperTEST(FooTest, DISABLED_DoesAbc) { ... } 190128f6c2f2SEnji Cooper 190228f6c2f2SEnji Cooperclass DISABLED_BarTest : public testing::Test { ... }; 190328f6c2f2SEnji Cooper 190428f6c2f2SEnji Cooper// Tests that Bar does Xyz. 190528f6c2f2SEnji CooperTEST_F(DISABLED_BarTest, DoesXyz) { ... } 190628f6c2f2SEnji Cooper``` 190728f6c2f2SEnji Cooper 190828f6c2f2SEnji Cooper{: .callout .note} 190928f6c2f2SEnji CooperNOTE: This feature should only be used for temporary pain-relief. You still have 191028f6c2f2SEnji Cooperto fix the disabled tests at a later date. As a reminder, GoogleTest will print 191128f6c2f2SEnji Coopera banner warning you if a test program contains any disabled tests. 191228f6c2f2SEnji Cooper 191328f6c2f2SEnji Cooper{: .callout .tip} 191428f6c2f2SEnji CooperTIP: You can easily count the number of disabled tests you have using 191528f6c2f2SEnji Cooper`grep`. This number can be used as a metric for 191628f6c2f2SEnji Cooperimproving your test quality. 191728f6c2f2SEnji Cooper 191828f6c2f2SEnji Cooper#### Temporarily Enabling Disabled Tests 191928f6c2f2SEnji Cooper 192028f6c2f2SEnji CooperTo include disabled tests in test execution, just invoke the test program with 192128f6c2f2SEnji Cooperthe `--gtest_also_run_disabled_tests` flag or set the 192228f6c2f2SEnji Cooper`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other than `0`. 192328f6c2f2SEnji CooperYou can combine this with the `--gtest_filter` flag to further select which 192428f6c2f2SEnji Cooperdisabled tests to run. 192528f6c2f2SEnji Cooper 192628f6c2f2SEnji Cooper### Repeating the Tests 192728f6c2f2SEnji Cooper 192828f6c2f2SEnji CooperOnce in a while you'll run into a test whose result is hit-or-miss. Perhaps it 192928f6c2f2SEnji Cooperwill fail only 1% of the time, making it rather hard to reproduce the bug under 193028f6c2f2SEnji Coopera debugger. This can be a major source of frustration. 193128f6c2f2SEnji Cooper 193228f6c2f2SEnji CooperThe `--gtest_repeat` flag allows you to repeat all (or selected) test methods in 193328f6c2f2SEnji Coopera program many times. Hopefully, a flaky test will eventually fail and give you 193428f6c2f2SEnji Coopera chance to debug. Here's how to use it: 193528f6c2f2SEnji Cooper 193628f6c2f2SEnji Cooper```none 193728f6c2f2SEnji Cooper$ foo_test --gtest_repeat=1000 193828f6c2f2SEnji CooperRepeat foo_test 1000 times and don't stop at failures. 193928f6c2f2SEnji Cooper 194028f6c2f2SEnji Cooper$ foo_test --gtest_repeat=-1 194128f6c2f2SEnji CooperA negative count means repeating forever. 194228f6c2f2SEnji Cooper 194328f6c2f2SEnji Cooper$ foo_test --gtest_repeat=1000 --gtest_break_on_failure 194428f6c2f2SEnji CooperRepeat foo_test 1000 times, stopping at the first failure. This 194528f6c2f2SEnji Cooperis especially useful when running under a debugger: when the test 194628f6c2f2SEnji Cooperfails, it will drop into the debugger and you can then inspect 194728f6c2f2SEnji Coopervariables and stacks. 194828f6c2f2SEnji Cooper 194928f6c2f2SEnji Cooper$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.* 195028f6c2f2SEnji CooperRepeat the tests whose name matches the filter 1000 times. 195128f6c2f2SEnji Cooper``` 195228f6c2f2SEnji Cooper 195328f6c2f2SEnji CooperIf your test program contains 195428f6c2f2SEnji Cooper[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be 195528f6c2f2SEnji Cooperrepeated in each iteration as well, as the flakiness may be in it. To avoid 195628f6c2f2SEnji Cooperrepeating global set-up/tear-down, specify 195728f6c2f2SEnji Cooper`--gtest_recreate_environments_when_repeating=false`{.nowrap}. 195828f6c2f2SEnji Cooper 195928f6c2f2SEnji CooperYou can also specify the repeat count by setting the `GTEST_REPEAT` environment 196028f6c2f2SEnji Coopervariable. 196128f6c2f2SEnji Cooper 196228f6c2f2SEnji Cooper### Shuffling the Tests 196328f6c2f2SEnji Cooper 196428f6c2f2SEnji CooperYou can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` 196528f6c2f2SEnji Cooperenvironment variable to `1`) to run the tests in a program in a random order. 196628f6c2f2SEnji CooperThis helps to reveal bad dependencies between tests. 196728f6c2f2SEnji Cooper 196828f6c2f2SEnji CooperBy default, GoogleTest uses a random seed calculated from the current time. 196928f6c2f2SEnji CooperTherefore you'll get a different order every time. The console output includes 197028f6c2f2SEnji Cooperthe random seed value, such that you can reproduce an order-related test failure 197128f6c2f2SEnji Cooperlater. To specify the random seed explicitly, use the `--gtest_random_seed=SEED` 197228f6c2f2SEnji Cooperflag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an 197328f6c2f2SEnji Cooperinteger in the range [0, 99999]. The seed value 0 is special: it tells 197428f6c2f2SEnji CooperGoogleTest to do the default behavior of calculating the seed from the current 197528f6c2f2SEnji Coopertime. 197628f6c2f2SEnji Cooper 197728f6c2f2SEnji CooperIf you combine this with `--gtest_repeat=N`, GoogleTest will pick a different 197828f6c2f2SEnji Cooperrandom seed and re-shuffle the tests in each iteration. 197928f6c2f2SEnji Cooper 198028f6c2f2SEnji Cooper### Distributing Test Functions to Multiple Machines 198128f6c2f2SEnji Cooper 198228f6c2f2SEnji CooperIf you have more than one machine you can use to run a test program, you might 198328f6c2f2SEnji Cooperwant to run the test functions in parallel and get the result faster. We call 198428f6c2f2SEnji Cooperthis technique *sharding*, where each machine is called a *shard*. 198528f6c2f2SEnji Cooper 198628f6c2f2SEnji CooperGoogleTest is compatible with test sharding. To take advantage of this feature, 198728f6c2f2SEnji Cooperyour test runner (not part of GoogleTest) needs to do the following: 198828f6c2f2SEnji Cooper 198928f6c2f2SEnji Cooper1. Allocate a number of machines (shards) to run the tests. 199028f6c2f2SEnji Cooper1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total 199128f6c2f2SEnji Cooper number of shards. It must be the same for all shards. 199228f6c2f2SEnji Cooper1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index 199328f6c2f2SEnji Cooper of the shard. Different shards must be assigned different indices, which 199428f6c2f2SEnji Cooper must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. 199528f6c2f2SEnji Cooper1. Run the same test program on all shards. When GoogleTest sees the above two 199628f6c2f2SEnji Cooper environment variables, it will select a subset of the test functions to run. 199728f6c2f2SEnji Cooper Across all shards, each test function in the program will be run exactly 199828f6c2f2SEnji Cooper once. 199928f6c2f2SEnji Cooper1. Wait for all shards to finish, then collect and report the results. 200028f6c2f2SEnji Cooper 200128f6c2f2SEnji CooperYour project may have tests that were written without GoogleTest and thus don't 200228f6c2f2SEnji Cooperunderstand this protocol. In order for your test runner to figure out which test 200328f6c2f2SEnji Coopersupports sharding, it can set the environment variable `GTEST_SHARD_STATUS_FILE` 200428f6c2f2SEnji Cooperto a non-existent file path. If a test program supports sharding, it will create 200528f6c2f2SEnji Cooperthis file to acknowledge that fact; otherwise it will not create it. The actual 200628f6c2f2SEnji Coopercontents of the file are not important at this time, although we may put some 200728f6c2f2SEnji Cooperuseful information in it in the future. 200828f6c2f2SEnji Cooper 200928f6c2f2SEnji CooperHere's an example to make it clear. Suppose you have a test program `foo_test` 201028f6c2f2SEnji Cooperthat contains the following 5 test functions: 201128f6c2f2SEnji Cooper 201228f6c2f2SEnji Cooper``` 201328f6c2f2SEnji CooperTEST(A, V) 201428f6c2f2SEnji CooperTEST(A, W) 201528f6c2f2SEnji CooperTEST(B, X) 201628f6c2f2SEnji CooperTEST(B, Y) 201728f6c2f2SEnji CooperTEST(B, Z) 201828f6c2f2SEnji Cooper``` 201928f6c2f2SEnji Cooper 202028f6c2f2SEnji CooperSuppose you have 3 machines at your disposal. To run the test functions in 202128f6c2f2SEnji Cooperparallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and set 202228f6c2f2SEnji Cooper`GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. Then you would 202328f6c2f2SEnji Cooperrun the same `foo_test` on each machine. 202428f6c2f2SEnji Cooper 202528f6c2f2SEnji CooperGoogleTest reserves the right to change how the work is distributed across the 202628f6c2f2SEnji Coopershards, but here's one possible scenario: 202728f6c2f2SEnji Cooper 202828f6c2f2SEnji Cooper* Machine #0 runs `A.V` and `B.X`. 202928f6c2f2SEnji Cooper* Machine #1 runs `A.W` and `B.Y`. 203028f6c2f2SEnji Cooper* Machine #2 runs `B.Z`. 203128f6c2f2SEnji Cooper 203228f6c2f2SEnji Cooper### Controlling Test Output 203328f6c2f2SEnji Cooper 203428f6c2f2SEnji Cooper#### Colored Terminal Output 203528f6c2f2SEnji Cooper 203628f6c2f2SEnji CooperGoogleTest can use colors in its terminal output to make it easier to spot the 203728f6c2f2SEnji Cooperimportant information: 203828f6c2f2SEnji Cooper 203928f6c2f2SEnji Cooper<pre>... 204028f6c2f2SEnji Cooper<font color="green">[----------]</font> 1 test from FooTest 204128f6c2f2SEnji Cooper<font color="green">[ RUN ]</font> FooTest.DoesAbc 204228f6c2f2SEnji Cooper<font color="green">[ OK ]</font> FooTest.DoesAbc 204328f6c2f2SEnji Cooper<font color="green">[----------]</font> 2 tests from BarTest 204428f6c2f2SEnji Cooper<font color="green">[ RUN ]</font> BarTest.HasXyzProperty 204528f6c2f2SEnji Cooper<font color="green">[ OK ]</font> BarTest.HasXyzProperty 204628f6c2f2SEnji Cooper<font color="green">[ RUN ]</font> BarTest.ReturnsTrueOnSuccess 204728f6c2f2SEnji Cooper... some error messages ... 204828f6c2f2SEnji Cooper<font color="red">[ FAILED ]</font> BarTest.ReturnsTrueOnSuccess 204928f6c2f2SEnji Cooper... 205028f6c2f2SEnji Cooper<font color="green">[==========]</font> 30 tests from 14 test suites ran. 205128f6c2f2SEnji Cooper<font color="green">[ PASSED ]</font> 28 tests. 205228f6c2f2SEnji Cooper<font color="red">[ FAILED ]</font> 2 tests, listed below: 205328f6c2f2SEnji Cooper<font color="red">[ FAILED ]</font> BarTest.ReturnsTrueOnSuccess 205428f6c2f2SEnji Cooper<font color="red">[ FAILED ]</font> AnotherTest.DoesXyz 205528f6c2f2SEnji Cooper 205628f6c2f2SEnji Cooper 2 FAILED TESTS 205728f6c2f2SEnji Cooper</pre> 205828f6c2f2SEnji Cooper 205928f6c2f2SEnji CooperYou can set the `GTEST_COLOR` environment variable or the `--gtest_color` 206028f6c2f2SEnji Coopercommand line flag to `yes`, `no`, or `auto` (the default) to enable colors, 206128f6c2f2SEnji Cooperdisable colors, or let GoogleTest decide. When the value is `auto`, GoogleTest 206228f6c2f2SEnji Cooperwill use colors if and only if the output goes to a terminal and (on non-Windows 206328f6c2f2SEnji Cooperplatforms) the `TERM` environment variable is set to `xterm` or `xterm-color`. 206428f6c2f2SEnji Cooper 206528f6c2f2SEnji Cooper#### Suppressing test passes 206628f6c2f2SEnji Cooper 206728f6c2f2SEnji CooperBy default, GoogleTest prints 1 line of output for each test, indicating if it 206828f6c2f2SEnji Cooperpassed or failed. To show only test failures, run the test program with 206928f6c2f2SEnji Cooper`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`. 207028f6c2f2SEnji Cooper 207128f6c2f2SEnji Cooper#### Suppressing the Elapsed Time 207228f6c2f2SEnji Cooper 207328f6c2f2SEnji CooperBy default, GoogleTest prints the time it takes to run each test. To disable 207428f6c2f2SEnji Cooperthat, run the test program with the `--gtest_print_time=0` command line flag, or 207528f6c2f2SEnji Cooperset the GTEST_PRINT_TIME environment variable to `0`. 207628f6c2f2SEnji Cooper 207728f6c2f2SEnji Cooper#### Suppressing UTF-8 Text Output 207828f6c2f2SEnji Cooper 207928f6c2f2SEnji CooperIn case of assertion failures, GoogleTest prints expected and actual values of 208028f6c2f2SEnji Coopertype `string` both as hex-encoded strings as well as in readable UTF-8 text if 208128f6c2f2SEnji Cooperthey contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 208228f6c2f2SEnji Coopertext because, for example, you don't have an UTF-8 compatible output medium, run 208328f6c2f2SEnji Cooperthe test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8` 208428f6c2f2SEnji Cooperenvironment variable to `0`. 208528f6c2f2SEnji Cooper 208628f6c2f2SEnji Cooper#### Generating an XML Report 208728f6c2f2SEnji Cooper 208828f6c2f2SEnji CooperGoogleTest can emit a detailed XML report to a file in addition to its normal 208928f6c2f2SEnji Coopertextual output. The report contains the duration of each test, and thus can help 209028f6c2f2SEnji Cooperyou identify slow tests. 209128f6c2f2SEnji Cooper 209228f6c2f2SEnji CooperTo generate the XML report, set the `GTEST_OUTPUT` environment variable or the 209328f6c2f2SEnji Cooper`--gtest_output` flag to the string `"xml:path_to_output_file"`, which will 209428f6c2f2SEnji Coopercreate the file at the given location. You can also just use the string `"xml"`, 209528f6c2f2SEnji Cooperin which case the output can be found in the `test_detail.xml` file in the 209628f6c2f2SEnji Coopercurrent directory. 209728f6c2f2SEnji Cooper 209828f6c2f2SEnji CooperIf you specify a directory (for example, `"xml:output/directory/"` on Linux or 209928f6c2f2SEnji Cooper`"xml:output\directory\"` on Windows), GoogleTest will create the XML file in 210028f6c2f2SEnji Cooperthat directory, named after the test executable (e.g. `foo_test.xml` for test 210128f6c2f2SEnji Cooperprogram `foo_test` or `foo_test.exe`). If the file already exists (perhaps left 210228f6c2f2SEnji Cooperover from a previous run), GoogleTest will pick a different name (e.g. 210328f6c2f2SEnji Cooper`foo_test_1.xml`) to avoid overwriting it. 210428f6c2f2SEnji Cooper 210528f6c2f2SEnji CooperThe report is based on the `junitreport` Ant task. Since that format was 210628f6c2f2SEnji Cooperoriginally intended for Java, a little interpretation is required to make it 210728f6c2f2SEnji Cooperapply to GoogleTest tests, as shown here: 210828f6c2f2SEnji Cooper 210928f6c2f2SEnji Cooper```xml 211028f6c2f2SEnji Cooper<testsuites name="AllTests" ...> 211128f6c2f2SEnji Cooper <testsuite name="test_case_name" ...> 211228f6c2f2SEnji Cooper <testcase name="test_name" ...> 211328f6c2f2SEnji Cooper <failure message="..."/> 211428f6c2f2SEnji Cooper <failure message="..."/> 211528f6c2f2SEnji Cooper <failure message="..."/> 211628f6c2f2SEnji Cooper </testcase> 211728f6c2f2SEnji Cooper </testsuite> 211828f6c2f2SEnji Cooper</testsuites> 211928f6c2f2SEnji Cooper``` 212028f6c2f2SEnji Cooper 212128f6c2f2SEnji Cooper* The root `<testsuites>` element corresponds to the entire test program. 212228f6c2f2SEnji Cooper* `<testsuite>` elements correspond to GoogleTest test suites. 212328f6c2f2SEnji Cooper* `<testcase>` elements correspond to GoogleTest test functions. 212428f6c2f2SEnji Cooper 212528f6c2f2SEnji CooperFor instance, the following program 212628f6c2f2SEnji Cooper 212728f6c2f2SEnji Cooper```c++ 212828f6c2f2SEnji CooperTEST(MathTest, Addition) { ... } 212928f6c2f2SEnji CooperTEST(MathTest, Subtraction) { ... } 213028f6c2f2SEnji CooperTEST(LogicTest, NonContradiction) { ... } 213128f6c2f2SEnji Cooper``` 213228f6c2f2SEnji Cooper 213328f6c2f2SEnji Coopercould generate this report: 213428f6c2f2SEnji Cooper 213528f6c2f2SEnji Cooper```xml 213628f6c2f2SEnji Cooper<?xml version="1.0" encoding="UTF-8"?> 213728f6c2f2SEnji Cooper<testsuites tests="3" failures="1" errors="0" time="0.035" timestamp="2011-10-31T18:52:42" name="AllTests"> 213828f6c2f2SEnji Cooper <testsuite name="MathTest" tests="2" failures="1" errors="0" time="0.015"> 213928f6c2f2SEnji Cooper <testcase name="Addition" file="test.cpp" line="1" status="run" time="0.007" classname=""> 214028f6c2f2SEnji Cooper <failure message="Value of: add(1, 1)
 Actual: 3
Expected: 2" type="">...</failure> 214128f6c2f2SEnji Cooper <failure message="Value of: add(1, -1)
 Actual: 1
Expected: 0" type="">...</failure> 214228f6c2f2SEnji Cooper </testcase> 214328f6c2f2SEnji Cooper <testcase name="Subtraction" file="test.cpp" line="2" status="run" time="0.005" classname=""> 214428f6c2f2SEnji Cooper </testcase> 214528f6c2f2SEnji Cooper </testsuite> 214628f6c2f2SEnji Cooper <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="0.005"> 214728f6c2f2SEnji Cooper <testcase name="NonContradiction" file="test.cpp" line="3" status="run" time="0.005" classname=""> 214828f6c2f2SEnji Cooper </testcase> 214928f6c2f2SEnji Cooper </testsuite> 215028f6c2f2SEnji Cooper</testsuites> 215128f6c2f2SEnji Cooper``` 215228f6c2f2SEnji Cooper 215328f6c2f2SEnji CooperThings to note: 215428f6c2f2SEnji Cooper 215528f6c2f2SEnji Cooper* The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how 215628f6c2f2SEnji Cooper many test functions the GoogleTest program or test suite contains, while the 215728f6c2f2SEnji Cooper `failures` attribute tells how many of them failed. 215828f6c2f2SEnji Cooper 215928f6c2f2SEnji Cooper* The `time` attribute expresses the duration of the test, test suite, or 216028f6c2f2SEnji Cooper entire test program in seconds. 216128f6c2f2SEnji Cooper 216228f6c2f2SEnji Cooper* The `timestamp` attribute records the local date and time of the test 216328f6c2f2SEnji Cooper execution. 216428f6c2f2SEnji Cooper 216528f6c2f2SEnji Cooper* The `file` and `line` attributes record the source file location, where the 216628f6c2f2SEnji Cooper test was defined. 216728f6c2f2SEnji Cooper 216828f6c2f2SEnji Cooper* Each `<failure>` element corresponds to a single failed GoogleTest 216928f6c2f2SEnji Cooper assertion. 217028f6c2f2SEnji Cooper 217128f6c2f2SEnji Cooper#### Generating a JSON Report 217228f6c2f2SEnji Cooper 217328f6c2f2SEnji CooperGoogleTest can also emit a JSON report as an alternative format to XML. To 217428f6c2f2SEnji Coopergenerate the JSON report, set the `GTEST_OUTPUT` environment variable or the 217528f6c2f2SEnji Cooper`--gtest_output` flag to the string `"json:path_to_output_file"`, which will 217628f6c2f2SEnji Coopercreate the file at the given location. You can also just use the string 217728f6c2f2SEnji Cooper`"json"`, in which case the output can be found in the `test_detail.json` file 217828f6c2f2SEnji Cooperin the current directory. 217928f6c2f2SEnji Cooper 218028f6c2f2SEnji CooperThe report format conforms to the following JSON Schema: 218128f6c2f2SEnji Cooper 218228f6c2f2SEnji Cooper```json 218328f6c2f2SEnji Cooper{ 2184*5ca8c28cSEnji Cooper "$schema": "https://json-schema.org/schema#", 218528f6c2f2SEnji Cooper "type": "object", 218628f6c2f2SEnji Cooper "definitions": { 218728f6c2f2SEnji Cooper "TestCase": { 218828f6c2f2SEnji Cooper "type": "object", 218928f6c2f2SEnji Cooper "properties": { 219028f6c2f2SEnji Cooper "name": { "type": "string" }, 219128f6c2f2SEnji Cooper "tests": { "type": "integer" }, 219228f6c2f2SEnji Cooper "failures": { "type": "integer" }, 219328f6c2f2SEnji Cooper "disabled": { "type": "integer" }, 219428f6c2f2SEnji Cooper "time": { "type": "string" }, 219528f6c2f2SEnji Cooper "testsuite": { 219628f6c2f2SEnji Cooper "type": "array", 219728f6c2f2SEnji Cooper "items": { 219828f6c2f2SEnji Cooper "$ref": "#/definitions/TestInfo" 219928f6c2f2SEnji Cooper } 220028f6c2f2SEnji Cooper } 220128f6c2f2SEnji Cooper } 220228f6c2f2SEnji Cooper }, 220328f6c2f2SEnji Cooper "TestInfo": { 220428f6c2f2SEnji Cooper "type": "object", 220528f6c2f2SEnji Cooper "properties": { 220628f6c2f2SEnji Cooper "name": { "type": "string" }, 220728f6c2f2SEnji Cooper "file": { "type": "string" }, 220828f6c2f2SEnji Cooper "line": { "type": "integer" }, 220928f6c2f2SEnji Cooper "status": { 221028f6c2f2SEnji Cooper "type": "string", 221128f6c2f2SEnji Cooper "enum": ["RUN", "NOTRUN"] 221228f6c2f2SEnji Cooper }, 221328f6c2f2SEnji Cooper "time": { "type": "string" }, 221428f6c2f2SEnji Cooper "classname": { "type": "string" }, 221528f6c2f2SEnji Cooper "failures": { 221628f6c2f2SEnji Cooper "type": "array", 221728f6c2f2SEnji Cooper "items": { 221828f6c2f2SEnji Cooper "$ref": "#/definitions/Failure" 221928f6c2f2SEnji Cooper } 222028f6c2f2SEnji Cooper } 222128f6c2f2SEnji Cooper } 222228f6c2f2SEnji Cooper }, 222328f6c2f2SEnji Cooper "Failure": { 222428f6c2f2SEnji Cooper "type": "object", 222528f6c2f2SEnji Cooper "properties": { 222628f6c2f2SEnji Cooper "failures": { "type": "string" }, 222728f6c2f2SEnji Cooper "type": { "type": "string" } 222828f6c2f2SEnji Cooper } 222928f6c2f2SEnji Cooper } 223028f6c2f2SEnji Cooper }, 223128f6c2f2SEnji Cooper "properties": { 223228f6c2f2SEnji Cooper "tests": { "type": "integer" }, 223328f6c2f2SEnji Cooper "failures": { "type": "integer" }, 223428f6c2f2SEnji Cooper "disabled": { "type": "integer" }, 223528f6c2f2SEnji Cooper "errors": { "type": "integer" }, 223628f6c2f2SEnji Cooper "timestamp": { 223728f6c2f2SEnji Cooper "type": "string", 223828f6c2f2SEnji Cooper "format": "date-time" 223928f6c2f2SEnji Cooper }, 224028f6c2f2SEnji Cooper "time": { "type": "string" }, 224128f6c2f2SEnji Cooper "name": { "type": "string" }, 224228f6c2f2SEnji Cooper "testsuites": { 224328f6c2f2SEnji Cooper "type": "array", 224428f6c2f2SEnji Cooper "items": { 224528f6c2f2SEnji Cooper "$ref": "#/definitions/TestCase" 224628f6c2f2SEnji Cooper } 224728f6c2f2SEnji Cooper } 224828f6c2f2SEnji Cooper } 224928f6c2f2SEnji Cooper} 225028f6c2f2SEnji Cooper``` 225128f6c2f2SEnji Cooper 225228f6c2f2SEnji CooperThe report uses the format that conforms to the following Proto3 using the 225328f6c2f2SEnji Cooper[JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): 225428f6c2f2SEnji Cooper 225528f6c2f2SEnji Cooper```proto 225628f6c2f2SEnji Coopersyntax = "proto3"; 225728f6c2f2SEnji Cooper 225828f6c2f2SEnji Cooperpackage googletest; 225928f6c2f2SEnji Cooper 226028f6c2f2SEnji Cooperimport "google/protobuf/timestamp.proto"; 226128f6c2f2SEnji Cooperimport "google/protobuf/duration.proto"; 226228f6c2f2SEnji Cooper 226328f6c2f2SEnji Coopermessage UnitTest { 226428f6c2f2SEnji Cooper int32 tests = 1; 226528f6c2f2SEnji Cooper int32 failures = 2; 226628f6c2f2SEnji Cooper int32 disabled = 3; 226728f6c2f2SEnji Cooper int32 errors = 4; 226828f6c2f2SEnji Cooper google.protobuf.Timestamp timestamp = 5; 226928f6c2f2SEnji Cooper google.protobuf.Duration time = 6; 227028f6c2f2SEnji Cooper string name = 7; 227128f6c2f2SEnji Cooper repeated TestCase testsuites = 8; 227228f6c2f2SEnji Cooper} 227328f6c2f2SEnji Cooper 227428f6c2f2SEnji Coopermessage TestCase { 227528f6c2f2SEnji Cooper string name = 1; 227628f6c2f2SEnji Cooper int32 tests = 2; 227728f6c2f2SEnji Cooper int32 failures = 3; 227828f6c2f2SEnji Cooper int32 disabled = 4; 227928f6c2f2SEnji Cooper int32 errors = 5; 228028f6c2f2SEnji Cooper google.protobuf.Duration time = 6; 228128f6c2f2SEnji Cooper repeated TestInfo testsuite = 7; 228228f6c2f2SEnji Cooper} 228328f6c2f2SEnji Cooper 228428f6c2f2SEnji Coopermessage TestInfo { 228528f6c2f2SEnji Cooper string name = 1; 228628f6c2f2SEnji Cooper string file = 6; 228728f6c2f2SEnji Cooper int32 line = 7; 228828f6c2f2SEnji Cooper enum Status { 228928f6c2f2SEnji Cooper RUN = 0; 229028f6c2f2SEnji Cooper NOTRUN = 1; 229128f6c2f2SEnji Cooper } 229228f6c2f2SEnji Cooper Status status = 2; 229328f6c2f2SEnji Cooper google.protobuf.Duration time = 3; 229428f6c2f2SEnji Cooper string classname = 4; 229528f6c2f2SEnji Cooper message Failure { 229628f6c2f2SEnji Cooper string failures = 1; 229728f6c2f2SEnji Cooper string type = 2; 229828f6c2f2SEnji Cooper } 229928f6c2f2SEnji Cooper repeated Failure failures = 5; 230028f6c2f2SEnji Cooper} 230128f6c2f2SEnji Cooper``` 230228f6c2f2SEnji Cooper 230328f6c2f2SEnji CooperFor instance, the following program 230428f6c2f2SEnji Cooper 230528f6c2f2SEnji Cooper```c++ 230628f6c2f2SEnji CooperTEST(MathTest, Addition) { ... } 230728f6c2f2SEnji CooperTEST(MathTest, Subtraction) { ... } 230828f6c2f2SEnji CooperTEST(LogicTest, NonContradiction) { ... } 230928f6c2f2SEnji Cooper``` 231028f6c2f2SEnji Cooper 231128f6c2f2SEnji Coopercould generate this report: 231228f6c2f2SEnji Cooper 231328f6c2f2SEnji Cooper```json 231428f6c2f2SEnji Cooper{ 231528f6c2f2SEnji Cooper "tests": 3, 231628f6c2f2SEnji Cooper "failures": 1, 231728f6c2f2SEnji Cooper "errors": 0, 231828f6c2f2SEnji Cooper "time": "0.035s", 231928f6c2f2SEnji Cooper "timestamp": "2011-10-31T18:52:42Z", 232028f6c2f2SEnji Cooper "name": "AllTests", 232128f6c2f2SEnji Cooper "testsuites": [ 232228f6c2f2SEnji Cooper { 232328f6c2f2SEnji Cooper "name": "MathTest", 232428f6c2f2SEnji Cooper "tests": 2, 232528f6c2f2SEnji Cooper "failures": 1, 232628f6c2f2SEnji Cooper "errors": 0, 232728f6c2f2SEnji Cooper "time": "0.015s", 232828f6c2f2SEnji Cooper "testsuite": [ 232928f6c2f2SEnji Cooper { 233028f6c2f2SEnji Cooper "name": "Addition", 233128f6c2f2SEnji Cooper "file": "test.cpp", 233228f6c2f2SEnji Cooper "line": 1, 233328f6c2f2SEnji Cooper "status": "RUN", 233428f6c2f2SEnji Cooper "time": "0.007s", 233528f6c2f2SEnji Cooper "classname": "", 233628f6c2f2SEnji Cooper "failures": [ 233728f6c2f2SEnji Cooper { 233828f6c2f2SEnji Cooper "message": "Value of: add(1, 1)\n Actual: 3\nExpected: 2", 233928f6c2f2SEnji Cooper "type": "" 234028f6c2f2SEnji Cooper }, 234128f6c2f2SEnji Cooper { 234228f6c2f2SEnji Cooper "message": "Value of: add(1, -1)\n Actual: 1\nExpected: 0", 234328f6c2f2SEnji Cooper "type": "" 234428f6c2f2SEnji Cooper } 234528f6c2f2SEnji Cooper ] 234628f6c2f2SEnji Cooper }, 234728f6c2f2SEnji Cooper { 234828f6c2f2SEnji Cooper "name": "Subtraction", 234928f6c2f2SEnji Cooper "file": "test.cpp", 235028f6c2f2SEnji Cooper "line": 2, 235128f6c2f2SEnji Cooper "status": "RUN", 235228f6c2f2SEnji Cooper "time": "0.005s", 235328f6c2f2SEnji Cooper "classname": "" 235428f6c2f2SEnji Cooper } 235528f6c2f2SEnji Cooper ] 235628f6c2f2SEnji Cooper }, 235728f6c2f2SEnji Cooper { 235828f6c2f2SEnji Cooper "name": "LogicTest", 235928f6c2f2SEnji Cooper "tests": 1, 236028f6c2f2SEnji Cooper "failures": 0, 236128f6c2f2SEnji Cooper "errors": 0, 236228f6c2f2SEnji Cooper "time": "0.005s", 236328f6c2f2SEnji Cooper "testsuite": [ 236428f6c2f2SEnji Cooper { 236528f6c2f2SEnji Cooper "name": "NonContradiction", 236628f6c2f2SEnji Cooper "file": "test.cpp", 236728f6c2f2SEnji Cooper "line": 3, 236828f6c2f2SEnji Cooper "status": "RUN", 236928f6c2f2SEnji Cooper "time": "0.005s", 237028f6c2f2SEnji Cooper "classname": "" 237128f6c2f2SEnji Cooper } 237228f6c2f2SEnji Cooper ] 237328f6c2f2SEnji Cooper } 237428f6c2f2SEnji Cooper ] 237528f6c2f2SEnji Cooper} 237628f6c2f2SEnji Cooper``` 237728f6c2f2SEnji Cooper 237828f6c2f2SEnji Cooper{: .callout .important} 237928f6c2f2SEnji CooperIMPORTANT: The exact format of the JSON document is subject to change. 238028f6c2f2SEnji Cooper 238128f6c2f2SEnji Cooper### Controlling How Failures Are Reported 238228f6c2f2SEnji Cooper 238328f6c2f2SEnji Cooper#### Detecting Test Premature Exit 238428f6c2f2SEnji Cooper 238528f6c2f2SEnji CooperGoogle Test implements the _premature-exit-file_ protocol for test runners to 238628f6c2f2SEnji Coopercatch any kind of unexpected exits of test programs. Upon start, Google Test 238728f6c2f2SEnji Coopercreates the file which will be automatically deleted after all work has been 238828f6c2f2SEnji Cooperfinished. Then, the test runner can check if this file exists. In case the file 238928f6c2f2SEnji Cooperremains undeleted, the inspected test has exited prematurely. 239028f6c2f2SEnji Cooper 239128f6c2f2SEnji CooperThis feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment 239228f6c2f2SEnji Coopervariable has been set. 239328f6c2f2SEnji Cooper 239428f6c2f2SEnji Cooper#### Turning Assertion Failures into Break-Points 239528f6c2f2SEnji Cooper 239628f6c2f2SEnji CooperWhen running test programs under a debugger, it's very convenient if the 239728f6c2f2SEnji Cooperdebugger can catch an assertion failure and automatically drop into interactive 239828f6c2f2SEnji Coopermode. GoogleTest's *break-on-failure* mode supports this behavior. 239928f6c2f2SEnji Cooper 240028f6c2f2SEnji CooperTo enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value 240128f6c2f2SEnji Cooperother than `0`. Alternatively, you can use the `--gtest_break_on_failure` 240228f6c2f2SEnji Coopercommand line flag. 240328f6c2f2SEnji Cooper 240428f6c2f2SEnji Cooper#### Disabling Catching Test-Thrown Exceptions 240528f6c2f2SEnji Cooper 240628f6c2f2SEnji CooperGoogleTest can be used either with or without exceptions enabled. If a test 240728f6c2f2SEnji Cooperthrows a C++ exception or (on Windows) a structured exception (SEH), by default 240828f6c2f2SEnji CooperGoogleTest catches it, reports it as a test failure, and continues with the next 240928f6c2f2SEnji Coopertest method. This maximizes the coverage of a test run. Also, on Windows an 241028f6c2f2SEnji Cooperuncaught exception will cause a pop-up window, so catching the exceptions allows 241128f6c2f2SEnji Cooperyou to run the tests automatically. 241228f6c2f2SEnji Cooper 241328f6c2f2SEnji CooperWhen debugging the test failures, however, you may instead want the exceptions 241428f6c2f2SEnji Cooperto be handled by the debugger, such that you can examine the call stack when an 241528f6c2f2SEnji Cooperexception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS` 241628f6c2f2SEnji Cooperenvironment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when 241728f6c2f2SEnji Cooperrunning the tests. 241828f6c2f2SEnji Cooper 241928f6c2f2SEnji Cooper### Sanitizer Integration 242028f6c2f2SEnji Cooper 242128f6c2f2SEnji CooperThe 242228f6c2f2SEnji Cooper[Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html), 242328f6c2f2SEnji Cooper[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer), 242428f6c2f2SEnji Cooperand 242528f6c2f2SEnji Cooper[Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual) 242628f6c2f2SEnji Cooperall provide weak functions that you can override to trigger explicit failures 242728f6c2f2SEnji Cooperwhen they detect sanitizer errors, such as creating a reference from `nullptr`. 242828f6c2f2SEnji CooperTo override these functions, place definitions for them in a source file that 242928f6c2f2SEnji Cooperyou compile as part of your main binary: 243028f6c2f2SEnji Cooper 243128f6c2f2SEnji Cooper``` 243228f6c2f2SEnji Cooperextern "C" { 243328f6c2f2SEnji Coopervoid __ubsan_on_report() { 243428f6c2f2SEnji Cooper FAIL() << "Encountered an undefined behavior sanitizer error"; 243528f6c2f2SEnji Cooper} 243628f6c2f2SEnji Coopervoid __asan_on_error() { 243728f6c2f2SEnji Cooper FAIL() << "Encountered an address sanitizer error"; 243828f6c2f2SEnji Cooper} 243928f6c2f2SEnji Coopervoid __tsan_on_report() { 244028f6c2f2SEnji Cooper FAIL() << "Encountered a thread sanitizer error"; 244128f6c2f2SEnji Cooper} 244228f6c2f2SEnji Cooper} // extern "C" 244328f6c2f2SEnji Cooper``` 244428f6c2f2SEnji Cooper 244528f6c2f2SEnji CooperAfter compiling your project with one of the sanitizers enabled, if a particular 244628f6c2f2SEnji Coopertest triggers a sanitizer error, GoogleTest will report that it failed. 2447