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