White Box Testing
Test your code
   Home      UnitTestingWithGoogletest
Google's framework for writing C++ tests on a variety of platforms (Linux, Mac OS X, Windows, Cygwin, Windows CE, and Symbian). Based on the xUnit architecture. Supports automatic test discovery, a rich set of assertions, user-defined assertions, death tests, fatal and non-fatal failures, value- and type-parameterized tests, various options for running the tests, and XML test report generation.
Google Test-related open source projects
Google Test UI is test runner that runs your test binary, allows you to track its progress via a progress bar, and displays a list of test failures. Clicking on one shows failure text. Google Test UI is written in C#.
GTest TAP Listener is an event listener for Google Test that implements the TAP protocol for test result output. If your test runner understands TAP, you may find it useful.
To write a test program using Google Test, you need to compile Google Test into a library and link your test with it. 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.
1) To create test fixture derive a class from ::testing::Test . Start its body with protected: or public:
                // The fixture for testing class Calc.
                class CalcTest : public ::testing::Test {
                                // Objects declared here can be used by all tests in the test case for Calc
                                                Calc *a, *b, *c;
                                // You can remove any or all of the following functions if its body
                                // is empty.
                                CalcTest() {
                                                // You can do set-up work for each test here.
                                                a = new Calc(10);
                                                b = new Calc(5);
                                                c = new Calc(10);
                                virtual ~CalcTest() {
                                                // You can do clean-up work that doesn't throw exceptions here.
                                                delete a;
                                                delete b;
                                                delete c;
                                // If the constructor and destructor are not enough for setting up
                                // and cleaning up each test, you can define the following methods:
                                virtualvoid SetUp() {
                                                // Code here will be called immediately after the constructor (right
                                                // before each test).
                                virtualvoid TearDown() {
                                                // Code here will be called immediately after each test (right
                                                // before the destructor).
2) Use the TEST() macro to define and name a test function as test case name and test name. When using a fixture, use TEST_F() instead of TEST() as it allows you to access objects and subroutines in the test fixture
TEST(test_case_name, test_name) {
 ... test body ...
TEST_F(test_case_name, test_name) {
 ... test body ...
3)To verify test results use Assert
Basic Assertions
These assertions do basic true/false condition testing.
Fatal assertion
Nonfatal assertion
condition is true
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.
Binary Comparison
This section describes assertions that compare two values.
Fatal assertion
Nonfatal assertion
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
String Comparison
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
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
the two C strings have different content, ignoring case
Explicit Success and Failure
These three assertions do not actually test a value or expression. Instead, they generate a success or failure directly. Like the macros that actually perform a test, you may stream a custom failure message into the them.
Generates a success. This does NOT make the overall test succeed. A test is considered successful only if none of its assertions fail during its execution.
Note: SUCCEED() is purely documentary and currently doesn't generate any user-visible output. However, we may add SUCCEED() messages to Google Test's output in the future.
FAIL() generates a fatal failure, while ADD_FAILURE() and ADD_FAILURE_AT() generate a nonfatal failure. These are useful when control flow, rather than a Boolean expression, deteremines the test's success or failure.
Exception Assertions
These are for verifying that a piece of code throws (or does not throw) an exception of the given type:
Fatal assertion
Nonfatal assertion
ASSERT_THROW(statement, exception_type);
EXPECT_THROW(statement, exception_type);
statement throws an exception of the given type
statement throws an exception of any type
statement doesn't throw any exception
Predicate Assertions for Better Error Messages
Even though Google Test has a rich set of assertions, they can never be complete, as it's impossible (nor a good idea) to anticipate all the scenarios a user might run into. Therefore, sometimes a user has to use EXPECT_TRUE() to check a complex expression, for lack of a better macro. This has the problem of not showing you the values of the parts of the expression, making it hard to understand what went wrong. As a workaround, some users choose to construct the failure message by themselves, streaming it into EXPECT_TRUE(). However, this is awkward especially when the expression has side-effects or is expensive to evaluate.
Google Test gives you three different options to solve this problem:
Using an Existing Boolean Function
If you already have a function or a functor that returns bool (or a type that can be implicitly converted to bool), you can use it in a predicate assertion to get the function arguments printed for free:
Fatal assertion
Nonfatal assertion
ASSERT_PRED1(pred1, val1);
EXPECT_PRED1(pred1, val1);
pred1(val1) returns true
ASSERT_PRED2(pred2, val1, val2);
EXPECT_PRED2(pred2, val1, val2);
pred2(val1, val2) returns true
                // Tests that the constructor.
                TEST_F(CalcTest, testConstructor)
                                // Set up
                                const double testOperand = 25;
                                Calc testcalc (testOperand);
                                // test
                                EXPECT_EQ( testOperand, testcalc.getOperand());
                // Tests that Calc does Plus.
                TEST_F(CalcTest, testPlus)
                                // Set up
                                Calc *result = new Calc(15);
                                ASSERT_TRUE( *a + *b == *result);
                // Tests that Calc does Minus.
                TEST_F(CalcTest, testMinus)
                                //set up
                                Calc *result = new Calc(5);
                                ASSERT_TRUE( *a - *b == *result);
                // Tests that Calc does Equal.
                TEST_F(CalcTest, testEqual)
                                ASSERT_TRUE( *a == *c );
                                ASSERT_TRUE( *a != *b );
                // Tests that Calc does Quotient.
                TEST_F(CalcTest, testQuotient)
                                EXPECT_EQ( 0, *a % *b);
4) 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:
  1. Saves the state of all Google Test flags.
  2. Creates a test fixture object for the first test.
  3. Initializes it via SetUp().
  4. Runs the test on the fixture object.
  5. Cleans up the fixture via TearDown().
  6. Deletes the fixture.
  7. Restores the state of all Google Test flags.
  8. Repeats the above steps for the next test, until all tests have run.
Download example code C++ Unit Testing With GoogleTest