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](https://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](https://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]: https://glossary.istqb.org/en_US/term/test-case-2 77[istqb test suite]: https://glossary.istqb.org/en_US/term/test-suite-1-3 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. See the following example, using 122the [`ASSERT_EQ` and `EXPECT_EQ`](reference/assertions.md#EXPECT_EQ) macros to 123verify value equality: 124 125```c++ 126ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; 127 128for (int i = 0; i < x.size(); ++i) { 129 EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; 130} 131``` 132 133Anything that can be streamed to an `ostream` can be streamed to an assertion 134macro--in particular, C strings and `string` objects. If a wide string 135(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is 136streamed to an assertion, it will be translated to UTF-8 when printed. 137 138GoogleTest provides a collection of assertions for verifying the behavior of 139your code in various ways. You can check Boolean conditions, compare values 140based on relational operators, verify string values, floating-point values, and 141much more. There are even assertions that enable you to verify more complex 142states by providing custom predicates. For the complete list of assertions 143provided by GoogleTest, see the [Assertions Reference](reference/assertions.md). 144 145## Simple Tests 146 147To create a test: 148 1491. Use the `TEST()` macro to define and name a test function. These are 150 ordinary C++ functions that don't return a value. 1512. In this function, along with any valid C++ statements you want to include, 152 use the various GoogleTest assertions to check values. 1533. The test's result is determined by the assertions; if any assertion in the 154 test fails (either fatally or non-fatally), or if the test crashes, the 155 entire test fails. Otherwise, it succeeds. 156 157```c++ 158TEST(TestSuiteName, TestName) { 159 ... test body ... 160} 161``` 162 163`TEST()` arguments go from general to specific. The *first* argument is the name 164of the test suite, and the *second* argument is the test's name within the test 165suite. Both names must be valid C++ identifiers, and they should not contain any 166underscores (`_`). A test's *full name* consists of its containing test suite 167and its individual name. Tests from different test suites can have the same 168individual name. 169 170For example, let's take a simple integer function: 171 172```c++ 173int Factorial(int n); // Returns the factorial of n 174``` 175 176A test suite for this function might look like: 177 178```c++ 179// Tests factorial of 0. 180TEST(FactorialTest, HandlesZeroInput) { 181 EXPECT_EQ(Factorial(0), 1); 182} 183 184// Tests factorial of positive numbers. 185TEST(FactorialTest, HandlesPositiveInput) { 186 EXPECT_EQ(Factorial(1), 1); 187 EXPECT_EQ(Factorial(2), 2); 188 EXPECT_EQ(Factorial(3), 6); 189 EXPECT_EQ(Factorial(8), 40320); 190} 191``` 192 193GoogleTest groups the test results by test suites, so logically related tests 194should be in the same test suite; in other words, the first argument to their 195`TEST()` should be the same. In the above example, we have two tests, 196`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test 197suite `FactorialTest`. 198 199When naming your test suites and tests, you should follow the same convention as 200for 201[naming functions and classes](https://google.github.io/styleguide/cppguide.html#Function_Names). 202 203**Availability**: Linux, Windows, Mac. 204 205## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests} 206 207If you find yourself writing two or more tests that operate on similar data, you 208can use a *test fixture*. This allows you to reuse the same configuration of 209objects for several different tests. 210 211To create a fixture: 212 2131. Derive a class from `testing::Test` . Start its body with `protected:`, as 214 we'll want to access fixture members from sub-classes. 2152. Inside the class, declare any objects you plan to use. 2163. If necessary, write a default constructor or `SetUp()` function to prepare 217 the objects for each test. A common mistake is to spell `SetUp()` as 218 **`Setup()`** with a small `u` - Use `override` in C++11 to make sure you 219 spelled it correctly. 2204. If necessary, write a destructor or `TearDown()` function to release any 221 resources you allocated in `SetUp()` . To learn when you should use the 222 constructor/destructor and when you should use `SetUp()/TearDown()`, read 223 the [FAQ](faq.md#CtorVsSetUp). 2245. If needed, define subroutines for your tests to share. 225 226When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to 227access objects and subroutines in the test fixture: 228 229```c++ 230TEST_F(TestFixtureClassName, TestName) { 231 ... test body ... 232} 233``` 234 235Unlike `TEST()`, in `TEST_F()` the first argument must be the name of the test 236fixture class. (`_F` stands for "Fixture"). No test suite name is specified for 237this macro. 238 239Unfortunately, the C++ macro system does not allow us to create a single macro 240that can handle both types of tests. Using the wrong macro causes a compiler 241error. 242 243Also, you must first define a test fixture class before using it in a 244`TEST_F()`, or you'll get the compiler error "`virtual outside class 245declaration`". 246 247For each test defined with `TEST_F()`, GoogleTest will create a *fresh* test 248fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean 249up by calling `TearDown()`, and then delete the test fixture. Note that 250different tests in the same test suite have different test fixture objects, and 251GoogleTest always deletes a test fixture before it creates the next one. 252GoogleTest does **not** reuse the same test fixture for multiple tests. Any 253changes one test makes to the fixture do not affect other tests. 254 255As an example, let's write tests for a FIFO queue class named `Queue`, which has 256the following interface: 257 258```c++ 259template <typename E> // E is the element type. 260class Queue { 261 public: 262 Queue(); 263 void Enqueue(const E& element); 264 E* Dequeue(); // Returns NULL if the queue is empty. 265 size_t size() const; 266 ... 267}; 268``` 269 270First, define a fixture class. By convention, you should give it the name 271`FooTest` where `Foo` is the class being tested. 272 273```c++ 274class QueueTest : public testing::Test { 275 protected: 276 QueueTest() { 277 // q0_ remains empty 278 q1_.Enqueue(1); 279 q2_.Enqueue(2); 280 q2_.Enqueue(3); 281 } 282 283 // ~QueueTest() override = default; 284 285 Queue<int> q0_; 286 Queue<int> q1_; 287 Queue<int> q2_; 288}; 289``` 290 291In this case, we don't need to define a destructor or a `TearDown()` method, 292because the implicit destructor generated by the compiler will perform all of 293the necessary cleanup. 294 295Now we'll write tests using `TEST_F()` and this fixture. 296 297```c++ 298TEST_F(QueueTest, IsEmptyInitially) { 299 EXPECT_EQ(q0_.size(), 0); 300} 301 302TEST_F(QueueTest, DequeueWorks) { 303 int* n = q0_.Dequeue(); 304 EXPECT_EQ(n, nullptr); 305 306 n = q1_.Dequeue(); 307 ASSERT_NE(n, nullptr); 308 EXPECT_EQ(*n, 1); 309 EXPECT_EQ(q1_.size(), 0); 310 delete n; 311 312 n = q2_.Dequeue(); 313 ASSERT_NE(n, nullptr); 314 EXPECT_EQ(*n, 2); 315 EXPECT_EQ(q2_.size(), 1); 316 delete n; 317} 318``` 319 320The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is 321to use `EXPECT_*` when you want the test to continue to reveal more errors after 322the assertion failure, and use `ASSERT_*` when continuing after failure doesn't 323make sense. For example, the second assertion in the `Dequeue` test is 324`ASSERT_NE(n, nullptr)`, as we need to dereference the pointer `n` later, which 325would lead to a segfault when `n` is `NULL`. 326 327When these tests run, the following happens: 328 3291. GoogleTest constructs a `QueueTest` object (let's call it `t1`). 3302. The first test (`IsEmptyInitially`) runs on `t1`. 3313. `t1` is destructed. 3324. The above steps are repeated on another `QueueTest` object, this time 333 running the `DequeueWorks` test. 334 335**Availability**: Linux, Windows, Mac. 336 337## Invoking the Tests 338 339`TEST()` and `TEST_F()` implicitly register their tests with GoogleTest. So, 340unlike with many other C++ testing frameworks, you don't have to re-list all 341your defined tests in order to run them. 342 343After defining your tests, you can run them with `RUN_ALL_TESTS()`, which 344returns `0` if all the tests are successful, or `1` otherwise. Note that 345`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from different 346test suites, or even different source files. 347 348When invoked, the `RUN_ALL_TESTS()` macro: 349 350* Saves the state of all GoogleTest flags. 351 352* Creates a test fixture object for the first test. 353 354* Initializes it via `SetUp()`. 355 356* Runs the test on the fixture object. 357 358* Cleans up the fixture via `TearDown()`. 359 360* Deletes the fixture. 361 362* Restores the state of all GoogleTest flags. 363 364* Repeats the above steps for the next test, until all tests have run. 365 366If a fatal failure happens the subsequent steps will be skipped. 367 368{: .callout .important} 369> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or 370> you will get a compiler error. The rationale for this design is that the 371> automated testing service determines whether a test has passed based on its 372> exit code, not on its stdout/stderr output; thus your `main()` function must 373> return the value of `RUN_ALL_TESTS()`. 374> 375> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than 376> once conflicts with some advanced GoogleTest features (e.g., thread-safe 377> [death tests](advanced.md#death-tests)) and thus is not supported. 378 379**Availability**: Linux, Windows, Mac. 380 381## Writing the main() Function 382 383Most users should *not* need to write their own `main` function and instead link 384with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry 385point. See the end of this section for details. The remainder of this section 386should only apply when you need to do something custom before the tests run that 387cannot be expressed within the framework of fixtures and test suites. 388 389If you write your own `main` function, it should return the value of 390`RUN_ALL_TESTS()`. 391 392You can start from this boilerplate: 393 394```c++ 395#include "this/package/foo.h" 396 397#include <gtest/gtest.h> 398 399namespace my { 400namespace project { 401namespace { 402 403// The fixture for testing class Foo. 404class FooTest : public testing::Test { 405 protected: 406 // You can remove any or all of the following functions if their bodies would 407 // be empty. 408 409 FooTest() { 410 // You can do set-up work for each test here. 411 } 412 413 ~FooTest() override { 414 // You can do clean-up work that doesn't throw exceptions here. 415 } 416 417 // If the constructor and destructor are not enough for setting up 418 // and cleaning up each test, you can define the following methods: 419 420 void SetUp() override { 421 // Code here will be called immediately after the constructor (right 422 // before each test). 423 } 424 425 void TearDown() override { 426 // Code here will be called immediately after each test (right 427 // before the destructor). 428 } 429 430 // Class members declared here can be used by all tests in the test suite 431 // for Foo. 432}; 433 434// Tests that the Foo::Bar() method does Abc. 435TEST_F(FooTest, MethodBarDoesAbc) { 436 const std::string input_filepath = "this/package/testdata/myinputfile.dat"; 437 const std::string output_filepath = "this/package/testdata/myoutputfile.dat"; 438 Foo f; 439 EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0); 440} 441 442// Tests that Foo does Xyz. 443TEST_F(FooTest, DoesXyz) { 444 // Exercises the Xyz feature of Foo. 445} 446 447} // namespace 448} // namespace project 449} // namespace my 450 451int main(int argc, char **argv) { 452 testing::InitGoogleTest(&argc, argv); 453 return RUN_ALL_TESTS(); 454} 455``` 456 457The `testing::InitGoogleTest()` function parses the command line for GoogleTest 458flags, and removes all recognized flags. This allows the user to control a test 459program's behavior via various flags, which we'll cover in the 460[AdvancedGuide](advanced.md). You **must** call this function before calling 461`RUN_ALL_TESTS()`, or the flags won't be properly initialized. 462 463On Windows, `InitGoogleTest()` also works with wide strings, so it can be used 464in programs compiled in `UNICODE` mode as well. 465 466But maybe you think that writing all those `main` functions is too much work? We 467agree with you completely, and that's why Google Test provides a basic 468implementation of main(). If it fits your needs, then just link your test with 469the `gtest_main` library and you are good to go. 470 471{: .callout .note} 472NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. 473 474## Known Limitations 475 476* Google Test is designed to be thread-safe. The implementation is thread-safe 477 on systems where the `pthreads` library is available. It is currently 478 *unsafe* to use Google Test assertions from two threads concurrently on 479 other systems (e.g. Windows). In most tests this is not an issue as usually 480 the assertions are done in the main thread. If you want to help, you can 481 volunteer to implement the necessary synchronization primitives in 482 `gtest-port.h` for your platform. 483