1# Googletest Primer 2 3 4## Introduction: Why googletest? 5 6*googletest* helps you write better C++ tests. 7 8googletest is a testing framework developed by the Testing 9Technology team with Google's specific 10requirements and constraints in mind. No matter whether you work on Linux, 11Windows, or a Mac, if you write C++ code, googletest can help you. And it 12supports *any* kind of tests, not just unit tests. 13 14So what makes a good test, and how does googletest fit in? We believe: 15 161. Tests should be *independent* and *repeatable*. It's a pain to debug a test 17 that succeeds or fails as a result of other tests. googletest isolates the 18 tests by running each of them on a different object. When a test fails, 19 googletest allows you to run it in isolation for quick debugging. 201. Tests should be well *organized* and reflect the structure of the tested 21 code. googletest groups related tests into test cases that can share data 22 and subroutines. This common pattern is easy to recognize and makes tests 23 easy to maintain. Such consistency is especially helpful when people switch 24 projects and start to work on a new code base. 251. Tests should be *portable* and *reusable*. Google has a lot of code that is 26 platform-neutral, its tests should also be platform-neutral. googletest 27 works on different OSes, with different compilers (gcc, icc, and MSVC), with 28 or without exceptions, so googletest tests can easily work with a variety of 29 configurations. 301. When tests fail, they should provide as much *information* about the problem 31 as possible. googletest doesn't stop at the first test failure. Instead, it 32 only stops the current test and continues with the next. You can also set up 33 tests that report non-fatal failures after which the current test continues. 34 Thus, you can detect and fix multiple bugs in a single run-edit-compile 35 cycle. 361. The testing framework should liberate test writers from housekeeping chores 37 and let them focus on the test *content*. googletest automatically keeps 38 track of all tests defined, and doesn't require the user to enumerate them 39 in order to run them. 401. Tests should be *fast*. With googletest, you can reuse shared resources 41 across tests and pay for the set-up/tear-down only once, without making 42 tests depend on each other. 43 44Since googletest is based on the popular xUnit architecture, you'll feel right 45at home if you've used JUnit or PyUnit before. If not, it will take you about 10 46minutes to learn the basics and get started. So let's go! 47 48## Beware of the nomenclature 49 50_Note:_ There might be some confusion of idea due to different 51definitions of the terms _Test_, _Test Case_ and _Test Suite_, so beware 52of misunderstanding these. 53 54Historically, googletest started to use the term _Test Case_ for grouping 55related tests, whereas current publications including the International Software 56Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) and various 57textbooks on Software Quality use the term _[Test 58Suite](http://glossary.istqb.org/search/test%20suite)_ for this. 59 60The related term _Test_, as it is used in the googletest, is corresponding to 61the term _[Test Case](http://glossary.istqb.org/search/test%20case)_ of ISTQB 62and others. 63 64The term _Test_ is commonly of broad enough sense, including ISTQB's definition 65of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as 66was used in Google Test is of contradictory sense and thus confusing. 67 68googletest recently started replacing the term _Test Case_ by _Test Suite_ The 69preferred API is TestSuite*. The older TestCase* API is being slowly deprecated 70and refactored away 71 72So please be aware of the different definitions of the terms: 73 74Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term 75:----------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- | :---------------------------------- 76Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case](http://glossary.istqb.org/search/test%20case) 77 78## Basic Concepts 79 80When using googletest, you start by writing *assertions*, which are statements 81that check whether a condition is true. An assertion's result can be *success*, 82*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the 83current function; otherwise the program continues normally. 84 85*Tests* use assertions to verify the tested code's behavior. If a test crashes 86or has a failed assertion, then it *fails*; otherwise it *succeeds*. 87 88A *test case* contains one or many tests. You should group your tests into test 89cases that reflect the structure of the tested code. When multiple tests in a 90test case need to share common objects and subroutines, you can put them into a 91*test fixture* class. 92 93A *test program* can contain multiple test cases. 94 95We'll now explain how to write a test program, starting at the individual 96assertion level and building up to tests and test cases. 97 98## Assertions 99 100googletest assertions are macros that resemble function calls. You test a class 101or function by making assertions about its behavior. When an assertion fails, 102googletest prints the assertion's source file and line number location, along 103with a failure message. You may also supply a custom failure message which will 104be appended to googletest's message. 105 106The assertions come in pairs that test the same thing but have different effects 107on the current function. `ASSERT_*` versions generate fatal failures when they 108fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal 109failures, which don't abort the current function. Usually `EXPECT_*` are 110preferred, as they allow more than one failure to be reported in a test. 111However, you should use `ASSERT_*` if it doesn't make sense to continue when the 112assertion in question fails. 113 114Since a failed `ASSERT_*` returns from the current function immediately, 115possibly skipping clean-up code that comes after it, it may cause a space leak. 116Depending on the nature of the leak, it may or may not be worth fixing - so keep 117this in mind if you get a heap checker error in addition to assertion errors. 118 119To provide a custom failure message, simply stream it into the macro using the 120`<<` operator, or a sequence of such operators. An example: 121 122```c++ 123ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; 124 125for (int i = 0; i < x.size(); ++i) { 126 EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; 127} 128``` 129 130Anything that can be streamed to an `ostream` can be streamed to an assertion 131macro--in particular, C strings and `string` objects. If a wide string 132(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is 133streamed to an assertion, it will be translated to UTF-8 when printed. 134 135### Basic Assertions 136 137These assertions do basic true/false condition testing. 138 139Fatal assertion | Nonfatal assertion | Verifies 140-------------------------- | -------------------------- | -------------------- 141`ASSERT_TRUE(condition);` | `EXPECT_TRUE(condition);` | `condition` is true 142`ASSERT_FALSE(condition);` | `EXPECT_FALSE(condition);` | `condition` is false 143 144Remember, when they fail, `ASSERT_*` yields a fatal failure and returns from the 145current function, while `EXPECT_*` yields a nonfatal failure, allowing the 146function to continue running. In either case, an assertion failure means its 147containing test fails. 148 149**Availability**: Linux, Windows, Mac. 150 151### Binary Comparison 152 153This section describes assertions that compare two values. 154 155Fatal assertion | Nonfatal assertion | Verifies 156------------------------ | ------------------------ | -------------- 157`ASSERT_EQ(val1, val2);` | `EXPECT_EQ(val1, val2);` | `val1 == val2` 158`ASSERT_NE(val1, val2);` | `EXPECT_NE(val1, val2);` | `val1 != val2` 159`ASSERT_LT(val1, val2);` | `EXPECT_LT(val1, val2);` | `val1 < val2` 160`ASSERT_LE(val1, val2);` | `EXPECT_LE(val1, val2);` | `val1 <= val2` 161`ASSERT_GT(val1, val2);` | `EXPECT_GT(val1, val2);` | `val1 > val2` 162`ASSERT_GE(val1, val2);` | `EXPECT_GE(val1, val2);` | `val1 >= val2` 163 164Value arguments must be comparable by the assertion's comparison operator or 165you'll get a compiler error. We used to require the arguments to support the 166`<<` operator for streaming to an `ostream`, but it's no longer necessary. If 167`<<` is supported, it will be called to print the arguments when the assertion 168fails; otherwise googletest will attempt to print them in the best way it can. 169For more details and how to customize the printing of the arguments, see 170gMock [recipe](../../googlemock/docs/CookBook.md#teaching-google-mock-how-to-print-your-values).). 171 172These assertions can work with a user-defined type, but only if you define the 173corresponding comparison operator (e.g. `==`, `<`, etc). Since this is 174discouraged by the Google [C++ Style 175Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading), 176you may need to use `ASSERT_TRUE()` or `EXPECT_TRUE()` to assert the equality of 177two objects of a user-defined type. 178 179However, when possible, `ASSERT_EQ(actual, expected)` is preferred to 180`ASSERT_TRUE(actual == expected)`, since it tells you `actual` and `expected`'s 181values on failure. 182 183Arguments are always evaluated exactly once. Therefore, it's OK for the 184arguments to have side effects. However, as with any ordinary C/C++ function, 185the arguments' evaluation order is undefined (i.e. the compiler is free to 186choose any order) and your code should not depend on any particular argument 187evaluation order. 188 189`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it 190tests if they are in the same memory location, not if they have the same value. 191Therefore, if you want to compare C strings (e.g. `const char*`) by value, use 192`ASSERT_STREQ()`, which will be described later on. In particular, to assert 193that a C string is `NULL`, use `ASSERT_STREQ(c_string, NULL)`. Consider using 194`ASSERT_EQ(c_string, nullptr)` if c++11 is supported. To compare two `string` 195objects, you should use `ASSERT_EQ`. 196 197When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)` 198instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is 199typed while `NULL` is not. See [FAQ](faq.md#why-does-googletest-support-expect_eqnull-ptr-and-assert_eqnull-ptr-but-not-expect_nenull-ptr-and-assert_nenull-ptr) 200for more details. 201 202If you're working with floating point numbers, you may want to use the floating 203point variations of some of these macros in order to avoid problems caused by 204rounding. See [Advanced googletest Topics](advanced.md) for details. 205 206Macros in this section work with both narrow and wide string objects (`string` 207and `wstring`). 208 209**Availability**: Linux, Windows, Mac. 210 211**Historical note**: Before February 2016 `*_EQ` had a convention of calling it 212as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now 213`*_EQ` treats both parameters in the same way. 214 215### String Comparison 216 217The assertions in this group compare two **C strings**. If you want to compare 218two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. 219 220| Fatal assertion | Nonfatal assertion | Verifies | 221| ------------------------------- | ------------------------------- | -------------------------------------------------------- | 222| `ASSERT_STREQ(str1, str2);` | `EXPECT_STREQ(str1, str2);` | the two C strings have the same content | 223| `ASSERT_STRNE(str1, str2);` | `EXPECT_STRNE(str1, str2);` | the two C strings have different contents | 224| `ASSERT_STRCASEEQ(str1, str2);` | `EXPECT_STRCASEEQ(str1, str2);` | the two C strings have the same content, ignoring case | 225| `ASSERT_STRCASENE(str1, str2);` | `EXPECT_STRCASENE(str1, str2);` | the two C strings have different contents, ignoring case | 226 227Note that "CASE" in an assertion name means that case is ignored. A `NULL` 228pointer and an empty string are considered *different*. 229 230`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a comparison 231of two wide strings fails, their values will be printed as UTF-8 narrow strings. 232 233**Availability**: Linux, Windows, Mac. 234 235**See also**: For more string comparison tricks (substring, prefix, suffix, and 236regular expression matching, for example), see 237[this](https://github.com/google/googletest/blob/master/googletest/docs/advanced.md) 238in the Advanced googletest Guide. 239 240## Simple Tests 241 242To create a test: 243 2441. Use the `TEST()` macro to define and name a test function, These are 245 ordinary C++ functions that don't return a value. 2461. In this function, along with any valid C++ statements you want to include, 247 use the various googletest assertions to check values. 2481. The test's result is determined by the assertions; if any assertion in the 249 test fails (either fatally or non-fatally), or if the test crashes, the 250 entire test fails. Otherwise, it succeeds. 251 252```c++ 253TEST(TestSuiteName, TestName) { 254 ... test body ... 255} 256``` 257 258`TEST()` arguments go from general to specific. The *first* argument is the name 259of the test case, and the *second* argument is the test's name within the test 260case. Both names must be valid C++ identifiers, and they should not contain 261underscore (`_`). A test's *full name* consists of its containing test case and 262its individual name. Tests from different test cases can have the same 263individual name. 264 265For example, let's take a simple integer function: 266 267```c++ 268int Factorial(int n); // Returns the factorial of n 269``` 270 271A test case for this function might look like: 272 273```c++ 274// Tests factorial of 0. 275TEST(FactorialTest, HandlesZeroInput) { 276 EXPECT_EQ(Factorial(0), 1); 277} 278 279// Tests factorial of positive numbers. 280TEST(FactorialTest, HandlesPositiveInput) { 281 EXPECT_EQ(Factorial(1), 1); 282 EXPECT_EQ(Factorial(2), 2); 283 EXPECT_EQ(Factorial(3), 6); 284 EXPECT_EQ(Factorial(8), 40320); 285} 286``` 287 288googletest groups the test results by test cases, so logically-related tests 289should be in the same test case; in other words, the first argument to their 290`TEST()` should be the same. In the above example, we have two tests, 291`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test case 292`FactorialTest`. 293 294When naming your test cases and tests, you should follow the same convention as 295for [naming functions and 296classes](https://google.github.io/styleguide/cppguide.html#Function_Names). 297 298**Availability**: Linux, Windows, Mac. 299 300## Test Fixtures: Using the Same Data Configuration for Multiple Tests 301 302If you find yourself writing two or more tests that operate on similar data, you 303can use a *test fixture*. It allows you to reuse the same configuration of 304objects for several different tests. 305 306To create a fixture: 307 3081. Derive a class from `::testing::Test` . Start its body with `protected:` as 309 we'll want to access fixture members from sub-classes. 3101. Inside the class, declare any objects you plan to use. 3111. If necessary, write a default constructor or `SetUp()` function to prepare 312 the objects for each test. A common mistake is to spell `SetUp()` as 313 **`Setup()`** with a small `u` - Use `override` in C++11 to make sure you 314 spelled it correctly 3151. If necessary, write a destructor or `TearDown()` function to release any 316 resources you allocated in `SetUp()` . To learn when you should use the 317 constructor/destructor and when you should use `SetUp()/TearDown()`, read 318 this [FAQ](faq.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-setupteardown) entry. 3191. If needed, define subroutines for your tests to share. 320 321When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to 322access objects and subroutines in the test fixture: 323 324```c++ 325TEST_F(TestSuiteName, TestName) { 326 ... test body ... 327} 328``` 329 330Like `TEST()`, the first argument is the test case name, but for `TEST_F()` this 331must be the name of the test fixture class. You've probably guessed: `_F` is for 332fixture. 333 334Unfortunately, the C++ macro system does not allow us to create a single macro 335that can handle both types of tests. Using the wrong macro causes a compiler 336error. 337 338Also, you must first define a test fixture class before using it in a 339`TEST_F()`, or you'll get the compiler error "`virtual outside class 340declaration`". 341 342For each test defined with `TEST_F()` , googletest will create a *fresh* test 343fixture at runtime, immediately initialize it via `SetUp()` , run the test, 344clean up by calling `TearDown()` , and then delete the test fixture. Note that 345different tests in the same test case have different test fixture objects, and 346googletest always deletes a test fixture before it creates the next one. 347googletest does **not** reuse the same test fixture for multiple tests. Any 348changes one test makes to the fixture do not affect other tests. 349 350As an example, let's write tests for a FIFO queue class named `Queue`, which has 351the following interface: 352 353```c++ 354template <typename E> // E is the element type. 355class Queue { 356 public: 357 Queue(); 358 void Enqueue(const E& element); 359 E* Dequeue(); // Returns NULL if the queue is empty. 360 size_t size() const; 361 ... 362}; 363``` 364 365First, define a fixture class. By convention, you should give it the name 366`FooTest` where `Foo` is the class being tested. 367 368```c++ 369class QueueTest : public ::testing::Test { 370 protected: 371 void SetUp() override { 372 q1_.Enqueue(1); 373 q2_.Enqueue(2); 374 q2_.Enqueue(3); 375 } 376 377 // void TearDown() override {} 378 379 Queue<int> q0_; 380 Queue<int> q1_; 381 Queue<int> q2_; 382}; 383``` 384 385In this case, `TearDown()` is not needed since we don't have to clean up after 386each test, other than what's already done by the destructor. 387 388Now we'll write tests using `TEST_F()` and this fixture. 389 390```c++ 391TEST_F(QueueTest, IsEmptyInitially) { 392 EXPECT_EQ(q0_.size(), 0); 393} 394 395TEST_F(QueueTest, DequeueWorks) { 396 int* n = q0_.Dequeue(); 397 EXPECT_EQ(n, nullptr); 398 399 n = q1_.Dequeue(); 400 ASSERT_NE(n, nullptr); 401 EXPECT_EQ(*n, 1); 402 EXPECT_EQ(q1_.size(), 0); 403 delete n; 404 405 n = q2_.Dequeue(); 406 ASSERT_NE(n, nullptr); 407 EXPECT_EQ(*n, 2); 408 EXPECT_EQ(q2_.size(), 1); 409 delete n; 410} 411``` 412 413The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is 414to use `EXPECT_*` when you want the test to continue to reveal more errors after 415the assertion failure, and use `ASSERT_*` when continuing after failure doesn't 416make sense. For example, the second assertion in the `Dequeue` test is 417=ASSERT_NE(nullptr, n)=, as we need to dereference the pointer `n` later, which 418would lead to a segfault when `n` is `NULL`. 419 420When these tests run, the following happens: 421 4221. googletest constructs a `QueueTest` object (let's call it `t1` ). 4231. `t1.SetUp()` initializes `t1` . 4241. The first test ( `IsEmptyInitially` ) runs on `t1` . 4251. `t1.TearDown()` cleans up after the test finishes. 4261. `t1` is destructed. 4271. The above steps are repeated on another `QueueTest` object, this time 428 running the `DequeueWorks` test. 429 430**Availability**: Linux, Windows, Mac. 431 432 433## Invoking the Tests 434 435`TEST()` and `TEST_F()` implicitly register their tests with googletest. So, 436unlike with many other C++ testing frameworks, you don't have to re-list all 437your defined tests in order to run them. 438 439After defining your tests, you can run them with `RUN_ALL_TESTS()` , which 440returns `0` if all the tests are successful, or `1` otherwise. Note that 441`RUN_ALL_TESTS()` runs *all tests* in your link unit -- they can be from 442different test cases, or even different source files. 443 444When invoked, the `RUN_ALL_TESTS()` macro: 445 4461. Saves the state of all googletest flags 447 448* Creates a test fixture object for the first test. 449 450* Initializes it via `SetUp()`. 451 452* Runs the test on the fixture object. 453 454* Cleans up the fixture via `TearDown()`. 455 456* Deletes the fixture. 457 458* Restores the state of all googletest flags 459 460* Repeats the above steps for the next test, until all tests have run. 461 462If a fatal failure happens the subsequent steps will be skipped. 463 464> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or 465> you will get a compiler error. The rationale for this design is that the 466> automated testing service determines whether a test has passed based on its 467> exit code, not on its stdout/stderr output; thus your `main()` function must 468> return the value of `RUN_ALL_TESTS()`. 469> 470> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than 471> once conflicts with some advanced googletest features (e.g. thread-safe [death 472> tests](advanced.md#death-tests)) and thus is not supported. 473 474**Availability**: Linux, Windows, Mac. 475 476## Writing the main() Function 477 478Write your own main() function, which should 479return the value of `RUN_ALL_TESTS()` 480 481```c++ 482#include "this/package/foo.h" 483#include "gtest/gtest.h" 484 485namespace { 486 487// The fixture for testing class Foo. 488class FooTest : public ::testing::Test { 489 protected: 490 // You can remove any or all of the following functions if its body 491 // is empty. 492 493 FooTest() { 494 // You can do set-up work for each test here. 495 } 496 497 ~FooTest() override { 498 // You can do clean-up work that doesn't throw exceptions here. 499 } 500 501 // If the constructor and destructor are not enough for setting up 502 // and cleaning up each test, you can define the following methods: 503 504 void SetUp() override { 505 // Code here will be called immediately after the constructor (right 506 // before each test). 507 } 508 509 void TearDown() override { 510 // Code here will be called immediately after each test (right 511 // before the destructor). 512 } 513 514 // Objects declared here can be used by all tests in the test case for Foo. 515}; 516 517// Tests that the Foo::Bar() method does Abc. 518TEST_F(FooTest, MethodBarDoesAbc) { 519 const std::string input_filepath = "this/package/testdata/myinputfile.dat"; 520 const std::string output_filepath = "this/package/testdata/myoutputfile.dat"; 521 Foo f; 522 EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0); 523} 524 525// Tests that Foo does Xyz. 526TEST_F(FooTest, DoesXyz) { 527 // Exercises the Xyz feature of Foo. 528} 529 530} // namespace 531 532int main(int argc, char **argv) { 533 ::testing::InitGoogleTest(&argc, argv); 534 return RUN_ALL_TESTS(); 535} 536``` 537 538 539The `::testing::InitGoogleTest()` function parses the command line for 540googletest flags, and removes all recognized flags. This allows the user to 541control a test program's behavior via various flags, which we'll cover in 542[AdvancedGuide](advanced.md). You **must** call this function before calling 543`RUN_ALL_TESTS()`, or the flags won't be properly initialized. 544 545On Windows, `InitGoogleTest()` also works with wide strings, so it can be used 546in programs compiled in `UNICODE` mode as well. 547 548But maybe you think that writing all those main() functions is too much work? We 549agree with you completely and that's why Google Test provides a basic 550implementation of main(). If it fits your needs, then just link your test with 551gtest\_main library and you are good to go. 552 553NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. 554 555 556## Known Limitations 557 558* Google Test is designed to be thread-safe. The implementation is thread-safe 559 on systems where the `pthreads` library is available. It is currently 560 _unsafe_ to use Google Test assertions from two threads concurrently on 561 other systems (e.g. Windows). In most tests this is not an issue as usually 562 the assertions are done in the main thread. If you want to help, you can 563 volunteer to implement the necessary synchronization primitives in 564 `gtest-port.h` for your platform. 565