Blame googletest/docs/Primer.md

Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
# Introduction: Why Google C++ Testing Framework? #
Packit bd1cd8
Packit bd1cd8
_Google C++ Testing Framework_ helps you write better C++ tests.
Packit bd1cd8
Packit bd1cd8
No matter whether you work on Linux, Windows, or a Mac, if you write C++ code,
Packit bd1cd8
Google Test can help you.
Packit bd1cd8
Packit bd1cd8
So what makes a good test, and how does Google C++ Testing Framework fit in? We believe:
Packit bd1cd8
  1. Tests should be _independent_ and _repeatable_. It's a pain to debug a test that succeeds or fails as a result of other tests.  Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging.
Packit bd1cd8
  1. Tests should be well _organized_ and reflect the structure of the tested code.  Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base.
Packit bd1cd8
  1. Tests should be _portable_ and _reusable_. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral.  Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations.  (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.)
Packit bd1cd8
  1. When tests fail, they should provide as much _information_ about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle.
Packit bd1cd8
  1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test _content_.  Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them.
Packit bd1cd8
  1. Tests should be _fast_. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other.
Packit bd1cd8
Packit bd1cd8
Since Google C++ Testing Framework is based on the popular xUnit
Packit bd1cd8
architecture, you'll feel right at home if you've used JUnit or PyUnit before.
Packit bd1cd8
If not, it will take you about 10 minutes to learn the basics and get started.
Packit bd1cd8
So let's go!
Packit bd1cd8
Packit bd1cd8
_Note:_ We sometimes refer to Google C++ Testing Framework informally
Packit bd1cd8
as _Google Test_.
Packit bd1cd8
Packit bd1cd8
# Setting up a New Test Project #
Packit bd1cd8
Packit bd1cd8
To write a test program using Google Test, you need to compile Google
Packit bd1cd8
Test into a library and link your test with it.  We provide build
Packit bd1cd8
files for some popular build systems: `msvc/` for Visual Studio,
Packit bd1cd8
`xcode/` for Mac Xcode, `make/` for GNU make, `codegear/` for Borland
Packit bd1cd8
C++ Builder, and the autotools script (deprecated) and
Packit bd1cd8
`CMakeLists.txt` for CMake (recommended) in the Google Test root
Packit bd1cd8
directory.  If your build system is not on this list, you can take a
Packit bd1cd8
look at `make/Makefile` to learn how Google Test should be compiled
Packit bd1cd8
(basically you want to compile `src/gtest-all.cc` with `GTEST_ROOT`
Packit bd1cd8
and `GTEST_ROOT/include` in the header search path, where `GTEST_ROOT`
Packit bd1cd8
is the Google Test root directory).
Packit bd1cd8
Packit bd1cd8
Once you are able to compile the Google Test library, you should
Packit bd1cd8
create a project or build target for your test program.  Make sure you
Packit bd1cd8
have `GTEST_ROOT/include` in the header search path so that the
Packit bd1cd8
compiler can find `"gtest/gtest.h"` when compiling your test.  Set up
Packit bd1cd8
your test project to link with the Google Test library (for example,
Packit bd1cd8
in Visual Studio, this is done by adding a dependency on
Packit bd1cd8
`gtest.vcproj`).
Packit bd1cd8
Packit bd1cd8
If you still have questions, take a look at how Google Test's own
Packit bd1cd8
tests are built and use them as examples.
Packit bd1cd8
Packit bd1cd8
# Basic Concepts #
Packit bd1cd8
Packit bd1cd8
When using Google Test, you start by writing _assertions_, which are statements
Packit bd1cd8
that check whether a condition is true. An assertion's result can be _success_,
Packit bd1cd8
_nonfatal failure_, or _fatal failure_. If a fatal failure occurs, it aborts
Packit bd1cd8
the current function; otherwise the program continues normally.
Packit bd1cd8
Packit bd1cd8
_Tests_ use assertions to verify the tested code's behavior. If a test crashes
Packit bd1cd8
or has a failed assertion, then it _fails_; otherwise it _succeeds_.
Packit bd1cd8
Packit bd1cd8
A _test case_ contains one or many tests. You should group your tests into test
Packit bd1cd8
cases that reflect the structure of the tested code. When multiple tests in a
Packit bd1cd8
test case need to share common objects and subroutines, you can put them into a
Packit bd1cd8
_test fixture_ class.
Packit bd1cd8
Packit bd1cd8
A _test program_ can contain multiple test cases.
Packit bd1cd8
Packit bd1cd8
We'll now explain how to write a test program, starting at the individual
Packit bd1cd8
assertion level and building up to tests and test cases.
Packit bd1cd8
Packit bd1cd8
# Assertions #
Packit bd1cd8
Packit bd1cd8
Google Test assertions are macros that resemble function calls. You test a
Packit bd1cd8
class or function by making assertions about its behavior. When an assertion
Packit bd1cd8
fails, Google Test prints the assertion's source file and line number location,
Packit bd1cd8
along with a failure message. You may also supply a custom failure message
Packit bd1cd8
which will be appended to Google Test's message.
Packit bd1cd8
Packit bd1cd8
The assertions come in pairs that test the same thing but have different
Packit bd1cd8
effects on the current function. `ASSERT_*` versions generate fatal failures
Packit bd1cd8
when they fail, and **abort the current function**. `EXPECT_*` versions generate
Packit bd1cd8
nonfatal failures, which don't abort the current function. Usually `EXPECT_*`
Packit bd1cd8
are preferred, as they allow more than one failures to be reported in a test.
Packit bd1cd8
However, you should use `ASSERT_*` if it doesn't make sense to continue when
Packit bd1cd8
the assertion in question fails.
Packit bd1cd8
Packit bd1cd8
Since a failed `ASSERT_*` returns from the current function immediately,
Packit bd1cd8
possibly skipping clean-up code that comes after it, it may cause a space leak.
Packit bd1cd8
Depending on the nature of the leak, it may or may not be worth fixing - so
Packit bd1cd8
keep this in mind if you get a heap checker error in addition to assertion
Packit bd1cd8
errors.
Packit bd1cd8
Packit bd1cd8
To provide a custom failure message, simply stream it into the macro using the
Packit bd1cd8
`<<` operator, or a sequence of such operators. An example:
Packit bd1cd8
```
Packit bd1cd8
ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
Packit bd1cd8
Packit bd1cd8
for (int i = 0; i < x.size(); ++i) {
Packit bd1cd8
  EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Anything that can be streamed to an `ostream` can be streamed to an assertion
Packit bd1cd8
macro--in particular, C strings and `string` objects. If a wide string
Packit bd1cd8
(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
Packit bd1cd8
streamed to an assertion, it will be translated to UTF-8 when printed.
Packit bd1cd8
Packit bd1cd8
## Basic Assertions ##
Packit bd1cd8
Packit bd1cd8
These assertions do basic true/false condition testing.
Packit bd1cd8
Packit bd1cd8
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
Packit bd1cd8
|:--------------------|:-----------------------|:-------------|
Packit bd1cd8
| `ASSERT_TRUE(`_condition_`)`;  | `EXPECT_TRUE(`_condition_`)`;   | _condition_ is true |
Packit bd1cd8
| `ASSERT_FALSE(`_condition_`)`; | `EXPECT_FALSE(`_condition_`)`;  | _condition_ is false |
Packit bd1cd8
Packit bd1cd8
Remember, when they fail, `ASSERT_*` yields a fatal failure and
Packit bd1cd8
returns from the current function, while `EXPECT_*` yields a nonfatal
Packit bd1cd8
failure, allowing the function to continue running. In either case, an
Packit bd1cd8
assertion failure means its containing test fails.
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
## Binary Comparison ##
Packit bd1cd8
Packit bd1cd8
This section describes assertions that compare two values.
Packit bd1cd8
Packit bd1cd8
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
Packit bd1cd8
|:--------------------|:-----------------------|:-------------|
Packit bd1cd8
|`ASSERT_EQ(`_val1_`, `_val2_`);`|`EXPECT_EQ(`_val1_`, `_val2_`);`| _val1_ `==` _val2_ |
Packit bd1cd8
|`ASSERT_NE(`_val1_`, `_val2_`);`|`EXPECT_NE(`_val1_`, `_val2_`);`| _val1_ `!=` _val2_ |
Packit bd1cd8
|`ASSERT_LT(`_val1_`, `_val2_`);`|`EXPECT_LT(`_val1_`, `_val2_`);`| _val1_ `<` _val2_ |
Packit bd1cd8
|`ASSERT_LE(`_val1_`, `_val2_`);`|`EXPECT_LE(`_val1_`, `_val2_`);`| _val1_ `<=` _val2_ |
Packit bd1cd8
|`ASSERT_GT(`_val1_`, `_val2_`);`|`EXPECT_GT(`_val1_`, `_val2_`);`| _val1_ `>` _val2_ |
Packit bd1cd8
|`ASSERT_GE(`_val1_`, `_val2_`);`|`EXPECT_GE(`_val1_`, `_val2_`);`| _val1_ `>=` _val2_ |
Packit bd1cd8
Packit bd1cd8
In the event of a failure, Google Test prints both _val1_ and _val2_.
Packit bd1cd8
Packit bd1cd8
Value arguments must be comparable by the assertion's comparison
Packit bd1cd8
operator or you'll get a compiler error.  We used to require the
Packit bd1cd8
arguments to support the `<<` operator for streaming to an `ostream`,
Packit bd1cd8
but it's no longer necessary since v1.6.0 (if `<<` is supported, it
Packit bd1cd8
will be called to print the arguments when the assertion fails;
Packit bd1cd8
otherwise Google Test will attempt to print them in the best way it
Packit bd1cd8
can. For more details and how to customize the printing of the
Packit bd1cd8
arguments, see this Google Mock [recipe](../../googlemock/docs/CookBook.md#teaching-google-mock-how-to-print-your-values).).
Packit bd1cd8
Packit bd1cd8
These assertions can work with a user-defined type, but only if you define the
Packit bd1cd8
corresponding comparison operator (e.g. `==`, `<`, etc).  If the corresponding
Packit bd1cd8
operator is defined, prefer using the `ASSERT_*()` macros because they will
Packit bd1cd8
print out not only the result of the comparison, but the two operands as well.
Packit bd1cd8
Packit bd1cd8
Arguments are always evaluated exactly once. Therefore, it's OK for the
Packit bd1cd8
arguments to have side effects. However, as with any ordinary C/C++ function,
Packit bd1cd8
the arguments' evaluation order is undefined (i.e. the compiler is free to
Packit bd1cd8
choose any order) and your code should not depend on any particular argument
Packit bd1cd8
evaluation order.
Packit bd1cd8
Packit bd1cd8
`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
Packit bd1cd8
tests if they are in the same memory location, not if they have the same value.
Packit bd1cd8
Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
Packit bd1cd8
`ASSERT_STREQ()` , which will be described later on. In particular, to assert
Packit bd1cd8
that a C string is `NULL`, use `ASSERT_STREQ(NULL, c_string)` . However, to
Packit bd1cd8
compare two `string` objects, you should use `ASSERT_EQ`.
Packit bd1cd8
Packit bd1cd8
Macros in this section work with both narrow and wide string objects (`string`
Packit bd1cd8
and `wstring`).
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
_Historical note_: Before February 2016 `*_EQ` had a convention of calling it as
Packit bd1cd8
`ASSERT_EQ(expected, actual)`, so lots of existing code uses this order.
Packit bd1cd8
Now `*_EQ` treats both parameters in the same way.
Packit bd1cd8
Packit bd1cd8
## String Comparison ##
Packit bd1cd8
Packit bd1cd8
The assertions in this group compare two **C strings**. If you want to compare
Packit bd1cd8
two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
Packit bd1cd8
Packit bd1cd8
| **Fatal assertion** | **Nonfatal assertion** | **Verifies** |
Packit bd1cd8
|:--------------------|:-----------------------|:-------------|
Packit bd1cd8
| `ASSERT_STREQ(`_str1_`, `_str2_`);`    | `EXPECT_STREQ(`_str1_`, `_str_2`);`     | the two C strings have the same content |
Packit bd1cd8
| `ASSERT_STRNE(`_str1_`, `_str2_`);`    | `EXPECT_STRNE(`_str1_`, `_str2_`);`     | the two C strings have different content |
Packit bd1cd8
| `ASSERT_STRCASEEQ(`_str1_`, `_str2_`);`| `EXPECT_STRCASEEQ(`_str1_`, `_str2_`);` | the two C strings have the same content, ignoring case |
Packit bd1cd8
| `ASSERT_STRCASENE(`_str1_`, `_str2_`);`| `EXPECT_STRCASENE(`_str1_`, `_str2_`);` | the two C strings have different content, ignoring case |
Packit bd1cd8
Packit bd1cd8
Note that "CASE" in an assertion name means that case is ignored.
Packit bd1cd8
Packit bd1cd8
`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a
Packit bd1cd8
comparison of two wide strings fails, their values will be printed as UTF-8
Packit bd1cd8
narrow strings.
Packit bd1cd8
Packit bd1cd8
A `NULL` pointer and an empty string are considered _different_.
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
See also: For more string comparison tricks (substring, prefix, suffix, and
Packit bd1cd8
regular expression matching, for example), see the [Advanced Google Test Guide](AdvancedGuide.md).
Packit bd1cd8
Packit bd1cd8
# Simple Tests #
Packit bd1cd8
Packit bd1cd8
To create a test:
Packit bd1cd8
  1. Use the `TEST()` macro to define and name a test function, These are ordinary C++ functions that don't return a value.
Packit bd1cd8
  1. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values.
Packit bd1cd8
  1. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TEST(test_case_name, test_name) {
Packit bd1cd8
 ... test body ...
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
`TEST()` arguments go from general to specific. The _first_ argument is the
Packit bd1cd8
name of the test case, and the _second_ argument is the test's name within the
Packit bd1cd8
test case. Both names must be valid C++ identifiers, and they should not contain underscore (`_`). A test's _full name_ consists of its containing test case and its
Packit bd1cd8
individual name. Tests from different test cases can have the same individual
Packit bd1cd8
name.
Packit bd1cd8
Packit bd1cd8
For example, let's take a simple integer function:
Packit bd1cd8
```
Packit bd1cd8
int Factorial(int n); // Returns the factorial of n
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
A test case for this function might look like:
Packit bd1cd8
```
Packit bd1cd8
// Tests factorial of 0.
Packit bd1cd8
TEST(FactorialTest, HandlesZeroInput) {
Packit bd1cd8
  EXPECT_EQ(1, Factorial(0));
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Tests factorial of positive numbers.
Packit bd1cd8
TEST(FactorialTest, HandlesPositiveInput) {
Packit bd1cd8
  EXPECT_EQ(1, Factorial(1));
Packit bd1cd8
  EXPECT_EQ(2, Factorial(2));
Packit bd1cd8
  EXPECT_EQ(6, Factorial(3));
Packit bd1cd8
  EXPECT_EQ(40320, Factorial(8));
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Google Test groups the test results by test cases, so logically-related tests
Packit bd1cd8
should be in the same test case; in other words, the first argument to their
Packit bd1cd8
`TEST()` should be the same. In the above example, we have two tests,
Packit bd1cd8
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
Packit bd1cd8
case `FactorialTest`.
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
# Test Fixtures: Using the Same Data Configuration for Multiple Tests #
Packit bd1cd8
Packit bd1cd8
If you find yourself writing two or more tests that operate on similar data,
Packit bd1cd8
you can use a _test fixture_. It allows you to reuse the same configuration of
Packit bd1cd8
objects for several different tests.
Packit bd1cd8
Packit bd1cd8
To create a fixture, just:
Packit bd1cd8
  1. Derive a class from `::testing::Test` . Start its body with `protected:` or `public:` as we'll want to access fixture members from sub-classes.
Packit bd1cd8
  1. Inside the class, declare any objects you plan to use.
Packit bd1cd8
  1. If necessary, write a default constructor or `SetUp()` function to prepare the objects for each test. A common mistake is to spell `SetUp()` as `Setup()` with a small `u` - don't let that happen to you.
Packit bd1cd8
  1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](FAQ.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-the-set-uptear-down-function).
Packit bd1cd8
  1. If needed, define subroutines for your tests to share.
Packit bd1cd8
Packit bd1cd8
When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
Packit bd1cd8
access objects and subroutines in the test fixture:
Packit bd1cd8
```
Packit bd1cd8
TEST_F(test_case_name, test_name) {
Packit bd1cd8
 ... test body ...
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Like `TEST()`, the first argument is the test case name, but for `TEST_F()`
Packit bd1cd8
this must be the name of the test fixture class. You've probably guessed: `_F`
Packit bd1cd8
is for fixture.
Packit bd1cd8
Packit bd1cd8
Unfortunately, the C++ macro system does not allow us to create a single macro
Packit bd1cd8
that can handle both types of tests. Using the wrong macro causes a compiler
Packit bd1cd8
error.
Packit bd1cd8
Packit bd1cd8
Also, you must first define a test fixture class before using it in a
Packit bd1cd8
`TEST_F()`, or you'll get the compiler error "`virtual outside class
Packit bd1cd8
declaration`".
Packit bd1cd8
Packit bd1cd8
For each test defined with `TEST_F()`, Google Test will:
Packit bd1cd8
  1. Create a _fresh_ test fixture at runtime
Packit bd1cd8
  1. Immediately initialize it via `SetUp()` ,
Packit bd1cd8
  1. Run the test
Packit bd1cd8
  1. Clean up by calling `TearDown()`
Packit bd1cd8
  1. Delete the test fixture.  Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests.
Packit bd1cd8
Packit bd1cd8
As an example, let's write tests for a FIFO queue class named `Queue`, which
Packit bd1cd8
has the following interface:
Packit bd1cd8
```
Packit bd1cd8
template <typename E> // E is the element type.
Packit bd1cd8
class Queue {
Packit bd1cd8
 public:
Packit bd1cd8
  Queue();
Packit bd1cd8
  void Enqueue(const E& element);
Packit bd1cd8
  E* Dequeue(); // Returns NULL if the queue is empty.
Packit bd1cd8
  size_t size() const;
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
First, define a fixture class. By convention, you should give it the name
Packit bd1cd8
`FooTest` where `Foo` is the class being tested.
Packit bd1cd8
```
Packit bd1cd8
class QueueTest : public ::testing::Test {
Packit bd1cd8
 protected:
Packit bd1cd8
  virtual void SetUp() {
Packit bd1cd8
    q1_.Enqueue(1);
Packit bd1cd8
    q2_.Enqueue(2);
Packit bd1cd8
    q2_.Enqueue(3);
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // virtual void TearDown() {}
Packit bd1cd8
Packit bd1cd8
  Queue<int> q0_;
Packit bd1cd8
  Queue<int> q1_;
Packit bd1cd8
  Queue<int> q2_;
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
In this case, `TearDown()` is not needed since we don't have to clean up after
Packit bd1cd8
each test, other than what's already done by the destructor.
Packit bd1cd8
Packit bd1cd8
Now we'll write tests using `TEST_F()` and this fixture.
Packit bd1cd8
```
Packit bd1cd8
TEST_F(QueueTest, IsEmptyInitially) {
Packit bd1cd8
  EXPECT_EQ(0, q0_.size());
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
TEST_F(QueueTest, DequeueWorks) {
Packit bd1cd8
  int* n = q0_.Dequeue();
Packit bd1cd8
  EXPECT_EQ(NULL, n);
Packit bd1cd8
Packit bd1cd8
  n = q1_.Dequeue();
Packit bd1cd8
  ASSERT_TRUE(n != NULL);
Packit bd1cd8
  EXPECT_EQ(1, *n);
Packit bd1cd8
  EXPECT_EQ(0, q1_.size());
Packit bd1cd8
  delete n;
Packit bd1cd8
Packit bd1cd8
  n = q2_.Dequeue();
Packit bd1cd8
  ASSERT_TRUE(n != NULL);
Packit bd1cd8
  EXPECT_EQ(2, *n);
Packit bd1cd8
  EXPECT_EQ(1, q2_.size());
Packit bd1cd8
  delete n;
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
Packit bd1cd8
to use `EXPECT_*` when you want the test to continue to reveal more errors
Packit bd1cd8
after the assertion failure, and use `ASSERT_*` when continuing after failure
Packit bd1cd8
doesn't make sense. For example, the second assertion in the `Dequeue` test is
Packit bd1cd8
`ASSERT_TRUE(n != NULL)`, as we need to dereference the pointer `n` later,
Packit bd1cd8
which would lead to a segfault when `n` is `NULL`.
Packit bd1cd8
Packit bd1cd8
When these tests run, the following happens:
Packit bd1cd8
  1. Google Test constructs a `QueueTest` object (let's call it `t1` ).
Packit bd1cd8
  1. `t1.SetUp()` initializes `t1` .
Packit bd1cd8
  1. The first test ( `IsEmptyInitially` ) runs on `t1` .
Packit bd1cd8
  1. `t1.TearDown()` cleans up after the test finishes.
Packit bd1cd8
  1. `t1` is destructed.
Packit bd1cd8
  1. The above steps are repeated on another `QueueTest` object, this time running the `DequeueWorks` test.
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
_Note_: Google Test automatically saves all _Google Test_ flags when a test
Packit bd1cd8
object is constructed, and restores them when it is destructed.
Packit bd1cd8
Packit bd1cd8
# Invoking the Tests #
Packit bd1cd8
Packit bd1cd8
`TEST()` and `TEST_F()` implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them.
Packit bd1cd8
Packit bd1cd8
After defining your tests, you can run them with `RUN_ALL_TESTS()` , which returns `0` if all the tests are successful, or `1` otherwise. Note that `RUN_ALL_TESTS()` runs _all tests_ in your link unit -- they can be from different test cases, or even different source files.
Packit bd1cd8
Packit bd1cd8
When invoked, the `RUN_ALL_TESTS()` macro:
Packit bd1cd8
  1. Saves the state of all  Google Test flags.
Packit bd1cd8
  1. Creates a test fixture object for the first test.
Packit bd1cd8
  1. Initializes it via `SetUp()`.
Packit bd1cd8
  1. Runs the test on the fixture object.
Packit bd1cd8
  1. Cleans up the fixture via `TearDown()`.
Packit bd1cd8
  1. Deletes the fixture.
Packit bd1cd8
  1. Restores the state of all Google Test flags.
Packit bd1cd8
  1. Repeats the above steps for the next test, until all tests have run.
Packit bd1cd8
Packit bd1cd8
In addition, if the text fixture's constructor generates a fatal failure in
Packit bd1cd8
step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly,
Packit bd1cd8
if step 3 generates a fatal failure, step 4 will be skipped.
Packit bd1cd8
Packit bd1cd8
_Important_: You must not ignore the return value of `RUN_ALL_TESTS()`, or `gcc`
Packit bd1cd8
will give you a compiler error. The rationale for this design is that the
Packit bd1cd8
automated testing service determines whether a test has passed based on its
Packit bd1cd8
exit code, not on its stdout/stderr output; thus your `main()` function must
Packit bd1cd8
return the value of `RUN_ALL_TESTS()`.
Packit bd1cd8
Packit bd1cd8
Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than once
Packit bd1cd8
conflicts with some advanced Google Test features (e.g. thread-safe death
Packit bd1cd8
tests) and thus is not supported.
Packit bd1cd8
Packit bd1cd8
_Availability_: Linux, Windows, Mac.
Packit bd1cd8
Packit bd1cd8
# Writing the main() Function #
Packit bd1cd8
Packit bd1cd8
You can start from this boilerplate:
Packit bd1cd8
```
Packit bd1cd8
#include "this/package/foo.h"
Packit bd1cd8
#include "gtest/gtest.h"
Packit bd1cd8
Packit bd1cd8
namespace {
Packit bd1cd8
Packit bd1cd8
// The fixture for testing class Foo.
Packit bd1cd8
class FooTest : public ::testing::Test {
Packit bd1cd8
 protected:
Packit bd1cd8
  // You can remove any or all of the following functions if its body
Packit bd1cd8
  // is empty.
Packit bd1cd8
Packit bd1cd8
  FooTest() {
Packit bd1cd8
    // You can do set-up work for each test here.
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  virtual ~FooTest() {
Packit bd1cd8
    // You can do clean-up work that doesn't throw exceptions here.
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // If the constructor and destructor are not enough for setting up
Packit bd1cd8
  // and cleaning up each test, you can define the following methods:
Packit bd1cd8
Packit bd1cd8
  virtual void SetUp() {
Packit bd1cd8
    // Code here will be called immediately after the constructor (right
Packit bd1cd8
    // before each test).
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  virtual void TearDown() {
Packit bd1cd8
    // Code here will be called immediately after each test (right
Packit bd1cd8
    // before the destructor).
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // Objects declared here can be used by all tests in the test case for Foo.
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
// Tests that the Foo::Bar() method does Abc.
Packit bd1cd8
TEST_F(FooTest, MethodBarDoesAbc) {
Packit bd1cd8
  const string input_filepath = "this/package/testdata/myinputfile.dat";
Packit bd1cd8
  const string output_filepath = "this/package/testdata/myoutputfile.dat";
Packit bd1cd8
  Foo f;
Packit bd1cd8
  EXPECT_EQ(0, f.Bar(input_filepath, output_filepath));
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Tests that Foo does Xyz.
Packit bd1cd8
TEST_F(FooTest, DoesXyz) {
Packit bd1cd8
  // Exercises the Xyz feature of Foo.
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
}  // namespace
Packit bd1cd8
Packit bd1cd8
int main(int argc, char **argv) {
Packit bd1cd8
  ::testing::InitGoogleTest(&argc, argv);
Packit bd1cd8
  return RUN_ALL_TESTS();
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The `::testing::InitGoogleTest()` function parses the command line for Google
Packit bd1cd8
Test flags, and removes all recognized flags. This allows the user to control a
Packit bd1cd8
test program's behavior via various flags, which we'll cover in [AdvancedGuide](AdvancedGuide.md).
Packit bd1cd8
You must call this function before calling `RUN_ALL_TESTS()`, or the flags
Packit bd1cd8
won't be properly initialized.
Packit bd1cd8
Packit bd1cd8
On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
Packit bd1cd8
in programs compiled in `UNICODE` mode as well.
Packit bd1cd8
Packit bd1cd8
But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest\_main library and you are good to go.
Packit bd1cd8
Packit bd1cd8
## Important note for Visual C++ users ##
Packit bd1cd8
If you put your tests into a library and your `main()` function is in a different library or in your .exe file, those tests will not run. The reason is a [bug](https://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=244410&siteid=210) in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function:
Packit bd1cd8
```
Packit bd1cd8
__declspec(dllexport) int PullInMyLibrary() { return 0; }
Packit bd1cd8
```
Packit bd1cd8
If you put your tests in a static library (not DLL) then `__declspec(dllexport)` is not required. Now, in your main program, write a code that invokes that function:
Packit bd1cd8
```
Packit bd1cd8
int PullInMyLibrary();
Packit bd1cd8
static int dummy = PullInMyLibrary();
Packit bd1cd8
```
Packit bd1cd8
This will keep your tests referenced and will make them register themselves at startup.
Packit bd1cd8
Packit bd1cd8
In addition, if you define your tests in a static library, add `/OPT:NOREF` to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to `Keep Unreferenced Data (/OPT:NOREF)`. This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable.
Packit bd1cd8
Packit bd1cd8
There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you _must_ change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries!
Packit bd1cd8
Packit bd1cd8
# Where to Go from Here #
Packit bd1cd8
Packit bd1cd8
Congratulations! You've learned the Google Test basics. You can start writing
Packit bd1cd8
and running Google Test tests, read some [samples](Samples.md), or continue with
Packit bd1cd8
[AdvancedGuide](AdvancedGuide.md), which describes many more useful Google Test features.
Packit bd1cd8
Packit bd1cd8
# Known Limitations #
Packit bd1cd8
Packit bd1cd8
Google Test is designed to be thread-safe.  The implementation is
Packit bd1cd8
thread-safe on systems where the `pthreads` library is available.  It
Packit bd1cd8
is currently _unsafe_ to use Google Test assertions from two threads
Packit bd1cd8
concurrently on other systems (e.g. Windows).  In most tests this is
Packit bd1cd8
not an issue as usually the assertions are done in the main thread. If
Packit bd1cd8
you want to help, you can volunteer to implement the necessary
Packit bd1cd8
synchronization primitives in `gtest-port.h` for your platform.