Introduction to the Google C + + unit testing Framework---gtest Framework

Source: Internet
Author: User
Tags assert

first, set up a new test project

before you write a test project with Google test, you need to compile gtest into the library and link the test to it. We have built files for some popular build systems: for msvc/ Visual Studio, for xcode/ Mac Xcode, for make/ GNU made, for codegear/ Borland C + + Builder.

If your build system is not on this list, there are autotools scripts (deprecated) and CMakeLists.txt CMake (recommended) in the googletest root directory. You can look at Make/makefile to see how to compile Google Test (basically you want to use Gtest_root and Gtest_root/include in the header file to compile the src/gtest-all.cc 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 goals for your test Program. Make sure you has GTEST_ROOT/include the header search path so, The compiler can find when "gtest/gtest.h" compiling your test. put Google te The St Library is added to your test project (e.g., adding dependencies on gtest.vcproj in vs).

Ii. Basic Concepts

When using Google testing, you first write an assertion that the assertion is a statement that checks whether the condition is True. The result of an assertion can be a success, a non-fatal failure, or a fatal failure. If a fatal failure occurs, it terminates the current function, or the program continues to run Normally.

Tests the behavior of using assertions to validate Code. If a test crashes or has a failed assertion, then the failure is unsuccessful;

One test case contains one or more Tests. You should group your tests into test cases that reflect the structure of your test 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.

Now we'll explain how to write a test program, start with a single assertion level, and build tests and test Cases.

third, assert

the Google Test assertion is a macro similar to a function call. You can test a class or function by asserting its behavior. When an assertion fails, Google test prints the source file and line number location of the assertion and the failure message. You can also provide a custom failure message that will be appended to the Google test Information.

Assertions are paired, testing the same thing, but having different effects on the current Function. The Assert_ * version generates a fatal error when it fails and aborts the current Function. expect_ * version generates a non-fatal failure and does not abort the current Function. Expect_ * is usually preferred because they allow multiple failures to be reported in the Test. however, If the function continues to run without meaning when it fails, you should use Assert_ *.

Because the failed Assert_ * immediately returns from the current function, it may skip the cleanup code behind it, which could cause a resource Leak. Depending on the nature of the leak, it may be worth repairing or it may not be worth repairing – so keep this in mind if you have a heap detection error to be aware of what is causing it.

To provide a custom failure message, simply stream it to a macro using the << operator or a series of such operators. An example:

Assert_eq (x.size (), y.size ()) << "Vectors x and y is of unequal length"; for (int i = 0; i < x.size (); ++i) {
   
    expect_eq (x[i], y[i]) << "Vectors x and y differ at index" << i;}
   

Example:

Expect_eq (0, strcmp (s.c_string (), kHelloString2)) << "s.c_string:" << s.c_string () << "khellostring: "<< +khellostring;

 

Anything that can be streamed to Ostream can be streamed to an assertion macro, especially a C string and a string object. If a wide string (wchar_t *,tchar * On Windows is in Unicode mode, or std:: Wstring) is streamed to an assertion, it will be converted to UTF-8 when Printing.

Iv. Basic Assertions

These assertions do a basic true/false conditional test.

Fatal Assertion Nonfatal Assertion verifies
ASSERT_TRUE(condition ) ; EXPECT_TRUE(condition ) ; condition is True
ASSERT_FALSE(condition ) ; EXPECT_FALSE(condition ) ; condition is False

Remember that when they fail, Assert_ * generates a fatal failure and returns from the current function, while expect_ * produces a non-fatal failure that allows the function to continue Running. In either case, an assertion failure means that the test it contains fails.

Five or two binary comparison

This section describes an assertion that compares two Values.

Fatal Assertion Nonfatal Assertion verifies
ASSERT_EQ(val1 , Val2); EXPECT_EQ(val1 , Val2); val1 == Val2
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 tests print both VAL1 and val2.

The value parameter must be comparable by asserting the comparison operator, or a compilation error will Occur. We have asked for the parameter support << operator for streaming to ostream, but from v1.6.0 it is no longer needed (if << is supported, it will be called when the assertion fails, otherwise google test will try to print them in the best way.) For more details and how to print a custom parameter, see this Google Mock recipe.

These assertions can use a user-defined type, but only if you have defined the appropriate comparison operator (for example, ==,<,etc). If you define the appropriate operators, you prefer to use the assert _ * () macro, because they will not only print the comparison results, but also print out two operands.

Parameters are always evaluated only once. therefore, the parameters have side effects that matter. however, like any normal c/s + + function, The order in which the parameters are evaluated is undefined ( that is, the compiler is free to choose any order ) and your code should not rely on any particular parameter evaluation Order.

Assert_eq () pointers have equal Pointers. If used on two C strings, it tests whether they are in the same memory location, instead of having the same value. so, If you want to compare the value of a C string (for example, a const char *), use Assert_streq (), which will be described later. In particular, to assert that the C string is NULL, use Assert_streq (null,c_string). however, to compare two string objects, you should use Assert_eq.

The macros in this section apply to narrow and wide string objects (string and wstring).

History: February 2016 ago * _eq has a convention called Assert_eq (expected,actual), so a lot of the existing code uses this Order. Now * _EQ handles both parameters in the same way.

six, string comparison

The assertions in this group compare the values of 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(str1 , str2); EXPECT_STREQ(str1 , _str_2); The C strings has the same content
ASSERT_STRNE(str1 , str2); EXPECT_STRNE(str1 , str2); The C strings has different content
ASSERT_STRCASEEQ(str1 , str2); EXPECT_STRCASEEQ(str1 , str2); The C strings has the same content, ignoring case (ignoring Capitalization)
ASSERT_STRCASENE(str1 , str2); EXPECT_STRCASENE(str1 , str2); The C strings has different content, ignoring case

Note that the "case" in the assertion name indicates that the casing is Ignored.

* Streq * and * Strne * Also accept the wide C string (wchar_t *). If a comparison of two wide strings fails, their values are 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 tips (for example, substrings, prefixes, suffixes, and regular expression matches), see the advanced Google testing Guide.

seven, Simple test

To create a test:

1. Use the test () macro to define and name testing functions, which are normal C + + functions that do not return a Value.
2. Use the various google test assertions to check the values in this function, together with any valid C + + statements that you want to Include.
3. The result of the test is determined by the assertion; If any assertion in the test fails (either fatal or non-fatal), or if the test crashes, the entire test fails. otherwise, it SUCCEEDS.

Test (test_case_name, test_name) {... test Body ...}

The TEST () parameter is from generic to Specific. The first parameter is the name of the test case, and the second parameter is the test name in the test case. Both names must be valid C + + identifiers, and they should not contain underscores (_). The full name of the test consists of the test case and its personal name that it contains. Tests from different test cases can have the same personal name.

For example, Let's use a simple integer function:

int factorial (int n); Returns the factorial of n;n!

  The test case for this function might resemble the following:

Tests factorial of 0.TEST (factorialtest, handleszeroinput) {  expect_eq (1, factorial (0));} Tests Factorial of positive numbers. TEST (factorialtest, handlespositiveinput) {  expect_eq (1, factorial (1));  Expect_eq (2, factorial (2));  Expect_eq (6, factorial (3));  Expect_eq (40320, factorial (8));}

Google test uses test cases to group test results, so that logically related tests should be in the same test case; In other words, the first parameter of their test () should be the Same. In the example above, we have two tests, handleszeroinput and handlespositiveinput, that belong to the same test case Factorialtest.

Testing fixture (test fixtures): Use the same data configuration for multiple tests

If you find yourself writing two or more tests to manipulate similar data, you can use a test fixture. It allows you to repeatedly use the same object configuration for several different tests.

To create a fixture, simply:

1. from:: testing:: Test derives a class. Use Protected: or public: start its body, because we want to access the fixture member from the SUBCLASS.
2. In the class, declare any objects that you intend to use.
3. If required, you can write a default constructor or Setup () function to prepare the object for each Test. A common mistake is to spell setup () for Setup () with a small u--don't let this happen to YOU.
4. If necessary, write a destructor or teardown () function to free any resources that you have allocated in Setup (). To learn when you should use constructors/destructors, read this FAQ entry when you should use Setup ()/TearDown ().
5. If necessary, define the subroutine for the test to be Shared.

When using a fixture, use Test_f () instead of test () because it allows you to access the objects and subroutines in the test fixture:

Test_f (test_case_name, test_name) {...} test Body ...}

Like Test (), The first parameter is a test case name,

But for Test_f () the first parameter must be the name of the test fixture class . You may have guessed it: _f is a fixture.

unfortunately, the C + + macro system does not allow us to create a macro that can handle two types of Tests. Using the wrong macro can cause a compiler error.

In addition, before you use it in Test_f (), you must first define a test fixture class, or you will get the compiler error "virtual outside class declaration".

For each test defined with Test_f (), Google test will:

1. Create a new test fixture at run time
2. Immediately through Setup () initialization,
3. Run the test
4. Clear by calling Teardown ()
5. Remove the test fixture. note that different tests in the same test case have different test fixture objects, and Google testing always removes the test fixture and then creates the next Test fixture. Google testing does not reuse the same test fixture for multiple Tests. one test any change to the fixture does not affect the other tests .

For example, Let's write a test for a FIFO queue class named queue, which has the following interfaces:

Template <typename E>//E is the element type.class queue {public:  queue ();  void Enqueue (const e& element);  e* Dequeue (); Returns NULL If the queue is Empty.  size_t size () const;  ...};

 first, Define a fixture class. By convention, you should give it the name footest, where Foo is the class being Tested.

Class queuetest:public:: testing::test {protected:  virtual void SetUp () {    q1_. Enqueue (1);    Q2_. Enqueue (2);    Q2_. Enqueue (3);  }  virtual void TearDown () {}  queue<int> q0_;  Queue<int> q1_;  Queue<int> q2_;};

In this case, teardown () is not required because we do not have to clean up after each test, except what the destructor has Done.

Now we will write the test using Test_f () and this fixture.

Test_f (queuetest, isemptyinitially) {  expect_eq (0, q0_.size ());} Test_f (queuetest, Dequeueworks) {  int* n = q0_. Dequeue ();  Expect_eq (NULL, n);  n = q1_. Dequeue ();  Assert_true (n! = NULL);  Expect_eq (1, *n);  Expect_eq (0, q1_.size ());  Delete n;  n = q2_. Dequeue ();  Assert_true (n! = NULL);  Expect_eq (2, *n);  Expect_eq (1, q2_.size ());  Delete n;}

The above uses Assert_ * and expect_ * assertions. The rule of thumb is to use expect_ * when you want the test to continue to show more errors after the assertion fails, or to continue using Assert_ * After the failure has no meaning. For example, the second assertion in the Dequeue test is assert_true (n! = null), because we need to dereference pointer n later, which causes N to be null when Segfault.

When these tests are run, the following happens:

1.Google test Constructs a Queuetest object (which we call t1).
2.t1. SetUp () initializes the t1.
3. The first Test (isemptyinitially) runs on t1.
4.t1. TearDown () cleans up after the test is Complete.
The 5.T1 is Reconstructed.
6. The above steps are repeated on another queuetest object, this time running the Dequeueworks Test.

nine, Call the test

Test () and Test_f () implicitly register their tests with Google Test. therefore, Unlike many other C + + test frameworks, You do not have to re-list all defined tests to run Them.

After you define the tests, you can run them using run_all_tests () and return 0 if all tests succeed, otherwise 1. Note thatrun_all_tests () runs all the tests in the linked unit -they can come from different test cases, even different source Files.

When called, the run_all_tests () macro:

1. Save the status of all Google test marks.
2. Create a test fixture object for the first Test.
3. Initialize it with Setup ().
4. Run the test on the fixture object.
5. Remove the fixture by Teardown ().
6. Remove the Fixture.
7. Restore the status of all Google test flags.
8. Repeat the previous steps for the next test until all test runs are Complete.

In addition, if the test Fixture's constructor generates a fatal failure in step 2, then step 3-5 has no meaning, so they are skipped. similarly, If step 3 generates a fatal failure, step 4 is Skipped.

Important: You cannot 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 test service determines whether the test has passed based on its exit code rather than its stdout/stderr output; therefore, your main () function must return the value of Run_all_tests () .

In addition, you should only call Run_all_tests () once. Calling it multiple times will conflict with some advanced Google testing features, such as a Thread-safe death test, and is therefore not supported.

Write the main function.

You can start with this sample:

#include "this/package/foo.h" #include "gtest/gtest.h" namespace {//the fixture for testing class Foo.class Footest:publi  c:: testing::test {protected://can Remove any or all of the following functions if it body//is Empty.  Footest () {//can do set-up work for each test here.  } virtual ~footest () {//you can do clean-up work that doesn ' t throw exceptions Here. }//If the constructor and destructor is not enough for setting Up//and cleaning up each test, you can define the fo llowing methods:virtual void SetUp () {//Code here is called immediately after the constructor (right//bef  Ore each test). } virtual void TearDown () {//Code here would be called immediately after each test (right//before the destructor  ). }//Objects declared here can is used by all tests in the test case for foo.};/ /Tests that the Foo::bar () method does Abc.test_f (footest, methodbardoesabc) {const string input_filepath = "this/packa Ge/testdata/myinputFile.dat ";  Const string Output_filepath = "this/package/testdata/myoutputfile.dat";  Foo f; Expect_eq (0, F.bar (input_filepath, output_filepath));}  Tests that Foo does xyz.test_f (footest, doesxyz) {//exercises the Xyz feature of foo.}}  Namespaceint main (int argc, char **argv) {:: testing::initgoogletest (&argc, argv); return run_all_tests ();}

:: testing:: initgoogletest () function parses the command line of the Google test flag and removes all identified flags. This allows the user to control the behavior of the test program through various flags, which we will introduce in Advancedguide. This function must be called before calling Run_all_tests (), otherwise the flag will not initialize CORRECTLY.

On windows, Initgoogletest () also applies to wide strings, so it can also be used in programs that are compiled in Unicode Mode.

But maybe you think that writing all of these main () functions is too much work? We fully agree with you, which is why Google test provides a basic implementation of main (). If it suits your needs, then just link your test with the Gtest_main library.

Xi. important notes for users of Visual C + +

If you put your test in a library, your main () function is in a different library or in Your. EXE file, these tests will not Run. The cause is an error in visual C + +. When you define a test, Google test creates some static objects to register Them. These objects are not referenced elsewhere, but their constructors should still Run. When the visual C + + linker discovers that the library is not referenced elsewhere, it throws the Library. You must refer to your library through the tests in the main program to prevent the linker from discarding it. Here's How It's Done. Declare a function in your library code:

。。。。。 omitted, if use VC again to See.

12, where to go from here

Congratulations! You've learned the basics of Google Testing. You can start writing and running google test tests, read some examples, or Continue reading advancedguide, which describes more useful Google testing Features.

13. Known Limitations

Google testing is designed for thread Safety. Implementations are thread-safe on systems that are available in the Pthreads library. currently, Google test assertions that use two threads at the same time on other systems, such as windows, are Unsafe. In most tests, this is not a problem, because the assertion is usually done in the main thread. If you want to help, you can volunteer to implement the necessary synchronization primitives for your platform in GTEST-PORT.H.

Introduction to the Google C + + unit testing Framework---gtest Framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.