3 <!-- GOOGLETEST_CM0036 DO NOT DELETE -->
5 <!-- GOOGLETEST_CM0035 DO NOT DELETE -->
7 ## Introduction: Why googletest?
9 *googletest* helps you write better C++ tests.
11 googletest is a testing framework developed by the Testing Technology team with
12 Google's specific requirements and constraints in mind. Whether you work on
13 Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it
14 supports *any* kind of tests, not just unit tests.
16 So what makes a good test, and how does googletest fit in? We believe:
18 1. Tests should be *independent* and *repeatable*. It's a pain to debug a test
19 that succeeds or fails as a result of other tests. googletest isolates the
20 tests by running each of them on a different object. When a test fails,
21 googletest allows you to run it in isolation for quick debugging.
22 2. Tests should be well *organized* and reflect the structure of the tested
23 code. googletest groups related tests into test suites that can share data
24 and subroutines. This common pattern is easy to recognize and makes tests
25 easy to maintain. Such consistency is especially helpful when people switch
26 projects and start to work on a new code base.
27 3. Tests should be *portable* and *reusable*. Google has a lot of code that is
28 platform-neutral; its tests should also be platform-neutral. googletest
29 works on different OSes, with different compilers, with or without
30 exceptions, so googletest tests can work with a variety of configurations.
31 4. When tests fail, they should provide as much *information* about the problem
32 as possible. googletest doesn't stop at the first test failure. Instead, it
33 only stops the current test and continues with the next. You can also set up
34 tests that report non-fatal failures after which the current test continues.
35 Thus, you can detect and fix multiple bugs in a single run-edit-compile
37 5. The testing framework should liberate test writers from housekeeping chores
38 and let them focus on the test *content*. googletest automatically keeps
39 track of all tests defined, and doesn't require the user to enumerate them
41 6. Tests should be *fast*. With googletest, you can reuse shared resources
42 across tests and pay for the set-up/tear-down only once, without making
43 tests depend on each other.
45 Since googletest is based on the popular xUnit architecture, you'll feel right
46 at home if you've used JUnit or PyUnit before. If not, it will take you about 10
47 minutes to learn the basics and get started. So let's go!
49 ## Beware of the nomenclature
51 _Note:_ There might be some confusion arising from different definitions of the
52 terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these.
54 Historically, googletest started to use the term _Test Case_ for grouping
55 related tests, whereas current publications, including International Software
56 Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and
57 various textbooks on software quality, use the term
58 _[Test Suite][istqb test suite]_ for this.
60 The related term _Test_, as it is used in googletest, corresponds to the term
61 _[Test Case][istqb test case]_ of ISTQB and others.
63 The term _Test_ is commonly of broad enough sense, including ISTQB's definition
64 of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as
65 was used in Google Test is of contradictory sense and thus confusing.
67 googletest recently started replacing the term _Test Case_ with _Test Suite_.
68 The preferred API is *TestSuite*. The older TestCase API is being slowly
69 deprecated and refactored away.
71 So please be aware of the different definitions of the terms:
73 <!-- mdformat off(github rendering does not support multiline tables) -->
75 Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term
76 :----------------------------------------------------------------------------------- | :---------------------- | :----------------------------------
77 Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
81 [istqb test case]: http://glossary.istqb.org/en/search/test%20case
82 [istqb test suite]: http://glossary.istqb.org/en/search/test%20suite
86 When using googletest, you start by writing *assertions*, which are statements
87 that check whether a condition is true. An assertion's result can be *success*,
88 *nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
89 current function; otherwise the program continues normally.
91 *Tests* use assertions to verify the tested code's behavior. If a test crashes
92 or has a failed assertion, then it *fails*; otherwise it *succeeds*.
94 A *test suite* contains one or many tests. You should group your tests into test
95 suites that reflect the structure of the tested code. When multiple tests in a
96 test suite need to share common objects and subroutines, you can put them into a
99 A *test program* can contain multiple test suites.
101 We'll now explain how to write a test program, starting at the individual
102 assertion level and building up to tests and test suites.
106 googletest assertions are macros that resemble function calls. You test a class
107 or function by making assertions about its behavior. When an assertion fails,
108 googletest prints the assertion's source file and line number location, along
109 with a failure message. You may also supply a custom failure message which will
110 be appended to googletest's message.
112 The assertions come in pairs that test the same thing but have different effects
113 on the current function. `ASSERT_*` versions generate fatal failures when they
114 fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal
115 failures, which don't abort the current function. Usually `EXPECT_*` are
116 preferred, as they allow more than one failure to be reported in a test.
117 However, you should use `ASSERT_*` if it doesn't make sense to continue when the
118 assertion in question fails.
120 Since a failed `ASSERT_*` returns from the current function immediately,
121 possibly skipping clean-up code that comes after it, it may cause a space leak.
122 Depending on the nature of the leak, it may or may not be worth fixing - so keep
123 this in mind if you get a heap checker error in addition to assertion errors.
125 To provide a custom failure message, simply stream it into the macro using the
126 `<<` operator or a sequence of such operators. An example:
129 ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
131 for (int i = 0; i < x.size(); ++i) {
132 EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
136 Anything that can be streamed to an `ostream` can be streamed to an assertion
137 macro--in particular, C strings and `string` objects. If a wide string
138 (`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
139 streamed to an assertion, it will be translated to UTF-8 when printed.
143 These assertions do basic true/false condition testing.
145 Fatal assertion | Nonfatal assertion | Verifies
146 -------------------------- | -------------------------- | --------------------
147 `ASSERT_TRUE(condition);` | `EXPECT_TRUE(condition);` | `condition` is true
148 `ASSERT_FALSE(condition);` | `EXPECT_FALSE(condition);` | `condition` is false
150 Remember, when they fail, `ASSERT_*` yields a fatal failure and returns from the
151 current function, while `EXPECT_*` yields a nonfatal failure, allowing the
152 function to continue running. In either case, an assertion failure means its
153 containing test fails.
155 **Availability**: Linux, Windows, Mac.
157 ### Binary Comparison
159 This section describes assertions that compare two values.
161 Fatal assertion | Nonfatal assertion | Verifies
162 ------------------------ | ------------------------ | --------------
163 `ASSERT_EQ(val1, val2);` | `EXPECT_EQ(val1, val2);` | `val1 == val2`
164 `ASSERT_NE(val1, val2);` | `EXPECT_NE(val1, val2);` | `val1 != val2`
165 `ASSERT_LT(val1, val2);` | `EXPECT_LT(val1, val2);` | `val1 < val2`
166 `ASSERT_LE(val1, val2);` | `EXPECT_LE(val1, val2);` | `val1 <= val2`
167 `ASSERT_GT(val1, val2);` | `EXPECT_GT(val1, val2);` | `val1 > val2`
168 `ASSERT_GE(val1, val2);` | `EXPECT_GE(val1, val2);` | `val1 >= val2`
170 Value arguments must be comparable by the assertion's comparison operator or
171 you'll get a compiler error. We used to require the arguments to support the
172 `<<` operator for streaming to an `ostream`, but this is no longer necessary. If
173 `<<` is supported, it will be called to print the arguments when the assertion
174 fails; otherwise googletest will attempt to print them in the best way it can.
175 For more details and how to customize the printing of the arguments, see the
176 [documentation](./advanced.md#teaching-googletest-how-to-print-your-values).
178 These assertions can work with a user-defined type, but only if you define the
179 corresponding comparison operator (e.g., `==` or `<`). Since this is discouraged
181 [C++ Style Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading),
182 you may need to use `ASSERT_TRUE()` or `EXPECT_TRUE()` to assert the equality of
183 two objects of a user-defined type.
185 However, when possible, `ASSERT_EQ(actual, expected)` is preferred to
186 `ASSERT_TRUE(actual == expected)`, since it tells you `actual` and `expected`'s
189 Arguments are always evaluated exactly once. Therefore, it's OK for the
190 arguments to have side effects. However, as with any ordinary C/C++ function,
191 the arguments' evaluation order is undefined (i.e., the compiler is free to
192 choose any order), and your code should not depend on any particular argument
195 `ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
196 tests if they are in the same memory location, not if they have the same value.
197 Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
198 `ASSERT_STREQ()`, which will be described later on. In particular, to assert
199 that a C string is `NULL`, use `ASSERT_STREQ(c_string, NULL)`. Consider using
200 `ASSERT_EQ(c_string, nullptr)` if c++11 is supported. To compare two `string`
201 objects, you should use `ASSERT_EQ`.
203 When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)`
204 instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is
205 typed, while `NULL` is not. See the [FAQ](faq.md) for more details.
207 If you're working with floating point numbers, you may want to use the floating
208 point variations of some of these macros in order to avoid problems caused by
209 rounding. See [Advanced googletest Topics](advanced.md) for details.
211 Macros in this section work with both narrow and wide string objects (`string`
214 **Availability**: Linux, Windows, Mac.
216 **Historical note**: Before February 2016 `*_EQ` had a convention of calling it
217 as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now
218 `*_EQ` treats both parameters in the same way.
220 ### String Comparison
222 The assertions in this group compare two **C strings**. If you want to compare
223 two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
225 <!-- mdformat off(github rendering does not support multiline tables) -->
227 | Fatal assertion | Nonfatal assertion | Verifies |
228 | -------------------------- | ------------------------------ | -------------------------------------------------------- |
229 | `ASSERT_STREQ(str1,str2);` | `EXPECT_STREQ(str1,str2);` | the two C strings have the same content |
230 | `ASSERT_STRNE(str1,str2);` | `EXPECT_STRNE(str1,str2);` | the two C strings have different contents |
231 | `ASSERT_STRCASEEQ(str1,str2);` | `EXPECT_STRCASEEQ(str1,str2);` | the two C strings have the same content, ignoring case |
232 | `ASSERT_STRCASENE(str1,str2);` | `EXPECT_STRCASENE(str1,str2);` | the two C strings have different contents, ignoring case |
236 Note that "CASE" in an assertion name means that case is ignored. A `NULL`
237 pointer and an empty string are considered *different*.
239 `*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a comparison
240 of two wide strings fails, their values will be printed as UTF-8 narrow strings.
242 **Availability**: Linux, Windows, Mac.
244 **See also**: For more string comparison tricks (substring, prefix, suffix, and
245 regular expression matching, for example), see [this](advanced.md) in the
246 Advanced googletest Guide.
252 1. Use the `TEST()` macro to define and name a test function. These are
253 ordinary C++ functions that don't return a value.
254 2. In this function, along with any valid C++ statements you want to include,
255 use the various googletest assertions to check values.
256 3. The test's result is determined by the assertions; if any assertion in the
257 test fails (either fatally or non-fatally), or if the test crashes, the
258 entire test fails. Otherwise, it succeeds.
261 TEST(TestSuiteName, TestName) {
266 `TEST()` arguments go from general to specific. The *first* argument is the name
267 of the test suite, and the *second* argument is the test's name within the test
268 suite. Both names must be valid C++ identifiers, and they should not contain
269 any underscores (`_`). A test's *full name* consists of its containing test suite and
270 its individual name. Tests from different test suites can have the same
273 For example, let's take a simple integer function:
276 int Factorial(int n); // Returns the factorial of n
279 A test suite for this function might look like:
282 // Tests factorial of 0.
283 TEST(FactorialTest, HandlesZeroInput) {
284 EXPECT_EQ(Factorial(0), 1);
287 // Tests factorial of positive numbers.
288 TEST(FactorialTest, HandlesPositiveInput) {
289 EXPECT_EQ(Factorial(1), 1);
290 EXPECT_EQ(Factorial(2), 2);
291 EXPECT_EQ(Factorial(3), 6);
292 EXPECT_EQ(Factorial(8), 40320);
296 googletest groups the test results by test suites, so logically related tests
297 should be in the same test suite; in other words, the first argument to their
298 `TEST()` should be the same. In the above example, we have two tests,
299 `HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
300 suite `FactorialTest`.
302 When naming your test suites and tests, you should follow the same convention as
304 [naming functions and classes](https://google.github.io/styleguide/cppguide.html#Function_Names).
306 **Availability**: Linux, Windows, Mac.
308 ## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests}
310 If you find yourself writing two or more tests that operate on similar data, you
311 can use a *test fixture*. This allows you to reuse the same configuration of
312 objects for several different tests.
316 1. Derive a class from `::testing::Test` . Start its body with `protected:`, as
317 we'll want to access fixture members from sub-classes.
318 2. Inside the class, declare any objects you plan to use.
319 3. If necessary, write a default constructor or `SetUp()` function to prepare
320 the objects for each test. A common mistake is to spell `SetUp()` as
321 **`Setup()`** with a small `u` - Use `override` in C++11 to make sure you
322 spelled it correctly.
323 4. If necessary, write a destructor or `TearDown()` function to release any
324 resources you allocated in `SetUp()` . To learn when you should use the
325 constructor/destructor and when you should use `SetUp()/TearDown()`, read
326 the [FAQ](faq.md#CtorVsSetUp).
327 5. If needed, define subroutines for your tests to share.
329 When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
330 access objects and subroutines in the test fixture:
333 TEST_F(TestFixtureName, TestName) {
338 Like `TEST()`, the first argument is the test suite name, but for `TEST_F()`
339 this must be the name of the test fixture class. You've probably guessed: `_F`
342 Unfortunately, the C++ macro system does not allow us to create a single macro
343 that can handle both types of tests. Using the wrong macro causes a compiler
346 Also, you must first define a test fixture class before using it in a
347 `TEST_F()`, or you'll get the compiler error "`virtual outside class
350 For each test defined with `TEST_F()`, googletest will create a *fresh* test
351 fixture at runtime, immediately initialize it via `SetUp()`, run the test,
352 clean up by calling `TearDown()`, and then delete the test fixture. Note that
353 different tests in the same test suite have different test fixture objects, and
354 googletest always deletes a test fixture before it creates the next one.
355 googletest does **not** reuse the same test fixture for multiple tests. Any
356 changes one test makes to the fixture do not affect other tests.
358 As an example, let's write tests for a FIFO queue class named `Queue`, which has
359 the following interface:
362 template <typename E> // E is the element type.
366 void Enqueue(const E& element);
367 E* Dequeue(); // Returns NULL if the queue is empty.
373 First, define a fixture class. By convention, you should give it the name
374 `FooTest` where `Foo` is the class being tested.
377 class QueueTest : public ::testing::Test {
379 void SetUp() override {
385 // void TearDown() override {}
393 In this case, `TearDown()` is not needed since we don't have to clean up after
394 each test, other than what's already done by the destructor.
396 Now we'll write tests using `TEST_F()` and this fixture.
399 TEST_F(QueueTest, IsEmptyInitially) {
400 EXPECT_EQ(q0_.size(), 0);
403 TEST_F(QueueTest, DequeueWorks) {
404 int* n = q0_.Dequeue();
405 EXPECT_EQ(n, nullptr);
408 ASSERT_NE(n, nullptr);
410 EXPECT_EQ(q1_.size(), 0);
414 ASSERT_NE(n, nullptr);
416 EXPECT_EQ(q2_.size(), 1);
421 The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
422 to use `EXPECT_*` when you want the test to continue to reveal more errors after
423 the assertion failure, and use `ASSERT_*` when continuing after failure doesn't
424 make sense. For example, the second assertion in the `Dequeue` test is
425 `ASSERT_NE(nullptr, n)`, as we need to dereference the pointer `n` later, which
426 would lead to a segfault when `n` is `NULL`.
428 When these tests run, the following happens:
430 1. googletest constructs a `QueueTest` object (let's call it `t1`).
431 2. `t1.SetUp()` initializes `t1`.
432 3. The first test (`IsEmptyInitially`) runs on `t1`.
433 4. `t1.TearDown()` cleans up after the test finishes.
434 5. `t1` is destructed.
435 6. The above steps are repeated on another `QueueTest` object, this time
436 running the `DequeueWorks` test.
438 **Availability**: Linux, Windows, Mac.
440 ## Invoking the Tests
442 `TEST()` and `TEST_F()` implicitly register their tests with googletest. So,
443 unlike with many other C++ testing frameworks, you don't have to re-list all
444 your defined tests in order to run them.
446 After defining your tests, you can run them with `RUN_ALL_TESTS()`, which
447 returns `0` if all the tests are successful, or `1` otherwise. Note that
448 `RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from
449 different test suites, or even different source files.
451 When invoked, the `RUN_ALL_TESTS()` macro:
453 * Saves the state of all googletest flags.
455 * Creates a test fixture object for the first test.
457 * Initializes it via `SetUp()`.
459 * Runs the test on the fixture object.
461 * Cleans up the fixture via `TearDown()`.
463 * Deletes the fixture.
465 * Restores the state of all googletest flags.
467 * Repeats the above steps for the next test, until all tests have run.
469 If a fatal failure happens the subsequent steps will be skipped.
471 > IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or
472 > you will get a compiler error. The rationale for this design is that the
473 > automated testing service determines whether a test has passed based on its
474 > exit code, not on its stdout/stderr output; thus your `main()` function must
475 > return the value of `RUN_ALL_TESTS()`.
477 > Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than
478 > once conflicts with some advanced googletest features (e.g., thread-safe
479 > [death tests](advanced.md#death-tests)) and thus is not supported.
481 **Availability**: Linux, Windows, Mac.
483 ## Writing the main() Function
485 Most users should _not_ need to write their own `main` function and instead link
486 with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry
487 point. See the end of this section for details. The remainder of this section
488 should only apply when you need to do something custom before the tests run that
489 cannot be expressed within the framework of fixtures and test suites.
491 If you write your own `main` function, it should return the value of
494 You can start from this boilerplate:
497 #include "this/package/foo.h"
499 #include "gtest/gtest.h"
505 // The fixture for testing class Foo.
506 class FooTest : public ::testing::Test {
508 // You can remove any or all of the following functions if their bodies would
512 // You can do set-up work for each test here.
515 ~FooTest() override {
516 // You can do clean-up work that doesn't throw exceptions here.
519 // If the constructor and destructor are not enough for setting up
520 // and cleaning up each test, you can define the following methods:
522 void SetUp() override {
523 // Code here will be called immediately after the constructor (right
524 // before each test).
527 void TearDown() override {
528 // Code here will be called immediately after each test (right
529 // before the destructor).
532 // Class members declared here can be used by all tests in the test suite
536 // Tests that the Foo::Bar() method does Abc.
537 TEST_F(FooTest, MethodBarDoesAbc) {
538 const std::string input_filepath = "this/package/testdata/myinputfile.dat";
539 const std::string output_filepath = "this/package/testdata/myoutputfile.dat";
541 EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0);
544 // Tests that Foo does Xyz.
545 TEST_F(FooTest, DoesXyz) {
546 // Exercises the Xyz feature of Foo.
550 } // namespace project
553 int main(int argc, char **argv) {
554 ::testing::InitGoogleTest(&argc, argv);
555 return RUN_ALL_TESTS();
559 The `::testing::InitGoogleTest()` function parses the command line for
560 googletest flags, and removes all recognized flags. This allows the user to
561 control a test program's behavior via various flags, which we'll cover in
562 the [AdvancedGuide](advanced.md). You **must** call this function before calling
563 `RUN_ALL_TESTS()`, or the flags won't be properly initialized.
565 On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
566 in programs compiled in `UNICODE` mode as well.
568 But maybe you think that writing all those `main` functions is too much work? We
569 agree with you completely, and that's why Google Test provides a basic
570 implementation of main(). If it fits your needs, then just link your test with
571 the `gtest_main` library and you are good to go.
573 NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
577 * Google Test is designed to be thread-safe. The implementation is thread-safe
578 on systems where the `pthreads` library is available. It is currently
579 _unsafe_ to use Google Test assertions from two threads concurrently on
580 other systems (e.g. Windows). In most tests this is not an issue as usually
581 the assertions are done in the main thread. If you want to help, you can
582 volunteer to implement the necessary synchronization primitives in
583 `gtest-port.h` for your platform.