proxygen
|
Google C++ Testing Framework helps you write better C++ tests.
No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, Google Test can help you.
So what makes a good test, and how does Google C++ Testing Framework fit in? We believe:
Since Google C++ Testing Framework is based on the popular xUnit architecture, you'll feel right at home if you've used JUnit or PyUnit before. If not, it will take you about 10 minutes to learn the basics and get started. So let's go!
Note: We sometimes refer to Google C++ Testing Framework informally as Google Test.
To write a test program using Google Test, you need to compile Google Test into a library and link your test with it. We provide build files for some popular build systems (msvc/
for Visual Studio, xcode/
for Mac Xcode, make/
for GNU make, codegear/
for Borland C++ Builder, and the autotools script in the Google Test root directory). If your build system is not on this list, you can take a look at make/Makefile
to learn how Google Test should be compiled (basically you want to compile src/gtest-all.cc
with GTEST_ROOT
and GTEST_ROOT/include
in the header search path, where GTEST_ROOT
is the Google Test root directory).
Once you are able to compile the Google Test library, you should create a project or build target for your test program. Make sure you have GTEST_ROOT/include
in the header search path so that the compiler can find <gtest/gtest.h>
when compiling your test. Set up your test project to link with the Google Test library (for example, in Visual Studio, this is done by adding a dependency on gtest.vcproj
).
If you still have questions, take a look at how Google Test's own tests are built and use them as examples.
When using Google Test, you start by writing assertions, which are statements that check whether a condition is true. An assertion's result can be success, nonfatal failure, or fatal failure. If a fatal failure occurs, it aborts the current function; otherwise the program continues normally.
Tests use assertions to verify the tested code's behavior. If a test crashes or has a failed assertion, then it fails; otherwise it succeeds.
A test case contains one or many tests. You should group your tests into test cases that reflect the structure of the tested code. When multiple tests in a test case need to share common objects and subroutines, you can put them into a test fixture class.
A test program can contain multiple test cases.
We'll now explain how to write a test program, starting at the individual assertion level and building up to tests and test cases.
Google Test assertions are macros that resemble function calls. You test a class or function by making assertions about its behavior. When an assertion fails, Google Test prints the assertion's source file and line number location, along with a failure message. You may also supply a custom failure message which will be appended to Google Test's message.
The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_*
versions generate fatal failures when they fail, and abort the current function. EXPECT_*
versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_*
are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_*
if it doesn't make sense to continue when the assertion in question fails.
Since a failed ASSERT_*
returns from the current function immediately, possibly skipping clean-up code that comes after it, it may cause a space leak. Depending on the nature of the leak, it may or may not be worth fixing - so keep this in mind if you get a heap checker error in addition to assertion errors.
To provide a custom failure message, simply stream it into the macro using the <<
operator, or a sequence of such operators. An example:
Anything that can be streamed to an ostream
can be streamed to an assertion macro–in particular, C strings and string
objects. If a wide string (wchar_t*
, TCHAR*
in UNICODE
mode on Windows, or std::wstring
) is streamed to an assertion, it will be translated to UTF-8 when printed.
These assertions do basic true/false condition testing.
Fatal assertion | Nonfatal assertion | Verifies |
---|---|---|
ASSERT_TRUE( _condition_) ; | EXPECT_TRUE( _condition_) ; | condition is true |
ASSERT_FALSE( _condition_) ; | EXPECT_FALSE( _condition_) ; | condition is false |
Remember, when they fail, ASSERT_*
yields a fatal failure and returns from the current function, while EXPECT_*
yields a nonfatal failure, allowing the function to continue running. In either case, an assertion failure means its containing test fails.
Availability: Linux, Windows, Mac.
This section describes assertions that compare two values.
Fatal assertion | Nonfatal assertion | Verifies |
---|---|---|
ASSERT_EQ( _expected_, _actual_); | EXPECT_EQ( _expected_, _actual_); | expected == actual |
ASSERT_NE( _val1_, _val2_); | EXPECT_NE( _val1_, _val2_); | val1 != val2 |
ASSERT_LT( _val1_, _val2_); | EXPECT_LT( _val1_, _val2_); | val1 < val2 |
ASSERT_LE( _val1_, _val2_); | EXPECT_LE( _val1_, _val2_); | val1 <= val2 |
ASSERT_GT( _val1_, _val2_); | EXPECT_GT( _val1_, _val2_); | val1 > val2 |
ASSERT_GE( _val1_, _val2_); | EXPECT_GE( _val1_, _val2_); | val1 >= val2 |
In the event of a failure, Google Test prints both val1 and val2 . In ASSERT_EQ*
and EXPECT_EQ*
(and all other equality assertions we'll introduce later), you should put the expression you want to test in the position of actual, and put its expected value in expected, as Google Test's failure messages are optimized for this convention.
Value arguments must be comparable by the assertion's comparison operator or you'll get a compiler error. Values must also support the <<
operator for streaming to an ostream
. All built-in types support this.
These assertions can work with a user-defined type, but only if you define the corresponding comparison operator (e.g. ==
, <
, etc). If the corresponding operator is defined, prefer using the ASSERT_*()
macros because they will print out not only the result of the comparison, but the two operands as well.
Arguments are always evaluated exactly once. Therefore, it's OK for the arguments to have side effects. However, as with any ordinary C/C++ function, the arguments' evaluation order is undefined (i.e. the compiler is free to choose any order) and your code should not depend on any particular argument evaluation order.
ASSERT_EQ()
does pointer equality on pointers. If used on two C strings, it tests if they are in the same memory location, not if they have the same value. Therefore, if you want to compare C strings (e.g. const char*
) by value, use ASSERT_STREQ()
, which will be described later on. In particular, to assert that a C string is NULL
, use ASSERT_STREQ(NULL, c_string)
. However, to compare two string
objects, you should use ASSERT_EQ
.
Macros in this section work with both narrow and wide string objects (string
and wstring
).
Availability: Linux, Windows, Mac.
The assertions in this group compare two C strings. If you want to compare two string
objects, use EXPECT_EQ
, EXPECT_NE
, and etc instead.
Fatal assertion | Nonfatal assertion | Verifies |
---|---|---|
ASSERT_STREQ( _expected_str_, _actual_str_); | EXPECT_STREQ( _expected_str_, _actual_str_); | the two C strings have the same content |
ASSERT_STRNE( _str1_, _str2_); | EXPECT_STRNE( _str1_, _str2_); | the two C strings have different content |
ASSERT_STRCASEEQ( _expected_str_, _actual_str_); | EXPECT_STRCASEEQ( _expected_str_, _actual_str_); | the two C strings have the same content, ignoring case |
ASSERT_STRCASENE( _str1_, _str2_); | EXPECT_STRCASENE( _str1_, _str2_); | the two C strings have different content, ignoring case |
Note that "CASE" in an assertion name means that case is ignored.
*STREQ*
and *STRNE*
also accept wide C strings (wchar_t*
). If a comparison of two wide strings fails, their values will be printed as UTF-8 narrow strings.
A NULL
pointer and an empty string are considered different.
Availability: Linux, Windows, Mac.
See also: For more string comparison tricks (substring, prefix, suffix, and regular expression matching, for example), see the [AdvancedGuide Advanced Google Test Guide].
To create a test:
TEST()
macro to define and name a test function, These are ordinary C++ functions that don't return a value.TEST()
arguments go from general to specific. The first argument is the name of the test case, and the second argument is the test's name within the test case. Remember that a test case can contain any number of individual tests. A test's full name consists of its containing test case and its individual name. Tests from different test cases can have the same individual name.
For example, let's take a simple integer function:
A test case for this function might look like:
Google Test groups the test results by test cases, so logically-related tests should be in the same test case; in other words, the first argument to their TEST()
should be the same. In the above example, we have two tests, HandlesZeroInput
and HandlesPositiveInput
, that belong to the same test case FactorialTest
.
Availability: Linux, Windows, Mac.
If you find yourself writing two or more tests that operate on similar data, you can use a test fixture. It allows you to reuse the same configuration of objects for several different tests.
To create a fixture, just:
testing::Test
. Start its body with protected:
or public:
as we'll want to access fixture members from sub-classes.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.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.When using a fixture, use TEST_F()
instead of TEST()
as it allows you to access objects and subroutines in the test fixture:
Like TEST()
, the first argument is the test case name, but for TEST_F()
this must be the name of the test fixture class. You've probably guessed: _F
is for fixture.
Unfortunately, the C++ macro system does not allow us to create a single macro that can handle both types of tests. Using the wrong macro causes a compiler error.
Also, you must first define a test fixture class before using it in a TEST_F()
, or you'll get the compiler error "`virtual outside class
declaration`".
For each test defined with TEST_F()
, Google Test will:
SetUp()
,TearDown()
As an example, let's write tests for a FIFO queue class named Queue
, which has the following interface:
First, define a fixture class. By convention, you should give it the name FooTest
where Foo
is the class being tested.
In this case, TearDown()
is not needed since we don't have to clean up after each test, other than what's already done by the destructor.
Now we'll write tests using TEST_F()
and this fixture.
The above uses both ASSERT_*
and EXPECT_*
assertions. The rule of thumb is to use EXPECT_*
when you want the test to continue to reveal more errors after the assertion failure, and use ASSERT_*
when continuing after failure doesn't make sense. For example, the second assertion in the Dequeue
test is ASSERT_TRUE(n != NULL)
, as we need to dereference the pointer n
later, which would lead to a segfault when n
is NULL
.
When these tests run, the following happens:
QueueTest
object (let's call it t1
).t1.SetUp()
initializes t1
.IsEmptyInitially
) runs on t1
.t1.TearDown()
cleans up after the test finishes.t1
is destructed.QueueTest
object, this time running the DequeueWorks
test.Availability: Linux, Windows, Mac.
Note: Google Test automatically saves all Google Test flags when a test object is constructed, and restores them when it is destructed.
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.
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.
When invoked, the RUN_ALL_TESTS()
macro:
SetUp()
.TearDown()
.In addition, if the text fixture's constructor generates a fatal failure in step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly, if step 3 generates a fatal failure, step 4 will be skipped.
Important: You must not ignore the return value of RUN_ALL_TESTS()
, or gcc
will give you a compiler error. The rationale for this design is that the automated testing service determines whether a test has passed based on its exit code, not on its stdout/stderr output; thus your main()
function must return the value of RUN_ALL_TESTS()
.
Also, you should call RUN_ALL_TESTS()
only once. Calling it more than once conflicts with some advanced Google Test features (e.g. thread-safe death tests) and thus is not supported.
Availability: Linux, Windows, Mac.
You can start from this boilerplate:
The testing::InitGoogleTest()
function parses the command line for Google Test flags, and removes all recognized flags. This allows the user to control a test program's behavior via various flags, which we'll cover in AdvancedGuide. You must call this function before calling RUN_ALL_TESTS()
, or the flags won't be properly initialized.
On Windows, InitGoogleTest()
also works with wide strings, so it can be used in programs compiled in UNICODE
mode as well.
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.
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 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:
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:
This will keep your tests referenced and will make them register themselves at startup.
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.
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!
Congratulations! You've learned the Google Test basics. You can start writing and running Google Test tests, read some samples, or continue with AdvancedGuide, which describes many more useful Google Test features.
Google Test is designed to be thread-safe. The implementation is thread-safe on systems where the pthreads
library is available. It is currently unsafe to use Google Test assertions from two threads concurrently on other systems (e.g. Windows). In most tests this is not an issue as usually the assertions are done in the main thread. If you want to help, you can volunteer to implement the necessary synchronization primitives in gtest-port.h
for your platform.