Google Open source C + + unit Testing Framework Google Test series __c++

Source: Internet
Author: User
Tags assert

Http://www.cnblogs.com/coderzh/archive/2009/04/06/1426755.html


Some time ago to learn and understand the next Google's Open source C + + unit Testing Framework Google test, referred to as gtest, very good. We used to be the implementation of their own set of unit testing framework, in the use of the process, found more and more use of inconvenience, and such inconvenience, gtest just very good solution.

In fact, the implementation of gtest itself is not complicated, we can completely imitate gtest, constantly improve our testing framework, but finally we decided to use Gtest to replace the original test framework, because:

1. Constantly improve our testing framework will find that the equivalent of the gtest again, although the wheel made very cool, but is not necessary.

2. Using gtest eliminates the hassle of maintaining the test framework, allowing us to devote more effort to the case design.

3.gtest improves the functionality and is easy to use, greatly improving the efficiency of writing test cases.

Gtest's official website is:

http://code.google.com/p/googletest/

From the official use of the document, you can almost get everything you want.

Http://code.google.com/p/googletest/wiki/GoogleTestPrimer

Http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide

If you want to gtest inside, just download the code to study it, this is the benefits of open source, ha.

The authorities have such a complete document, why do I have to write it. On the one hand, I remember notes, good memory is not as bad as writing, after their own want to check some usage can also be directly found here, on the one hand is for not want to see a lot of English documents friends, here I can quickly find gtest related content.


Additional articles:

How to jump out of current test cases in 1.gtest

2. Write beautiful gtest test Cases

3.gtest Parameterized Test code sample (with complete engineering examples)



play to Google Open source C + + unit Test framework Google Test series (gtest) one-first knowledge gtest

First, the preface

This article will introduce some of the basic uses of gtest, including downloading, installing, compiling, building our first Test demo project, and writing one of the simplest test cases.
Second, download

If you do not remember the Web site, directly in Google search Gtest, the first is. Currently the latest version of Gtest is 1.3.0, which can be downloaded to the latest version from the following addresses:

Http://googletest.googlecode.com/files/gtest-1.3.0.zip

Http://googletest.googlecode.com/files/gtest-1.3.0.tar.gz

HTTP://GOOGLETEST.GOOGLECODE.COM/FILES/GTEST-1.3.0.TAR.BZ2 three, compile

After decompression, there is a msvc directory:

Use VS students can directly open MSVC inside the project file, if you are using VS2005 or VS2008, open will prompt you to upgrade, after the level, we directly compile inside the "Gtest" project, you can directly edit the.

Here to remind you that if you upgrade to VS2008 project, then your test demo is the best VS2008 project, or you will find very depressed, your demo how also make up but, I have been tossing for a long time, when I upgraded to VS2008 project, As a result, I use VS2005 project to build demo, anyway. (There is a misunderstanding here, not that it can only be compiled in VS2008, but also in VS2005.) If you want to compile the VS2005 version, it is best to ensure that gtest and your test project are using VS2005 engineering. )

After compiling, see the compiled gtestd.lib or gtest.lib file in the Debug or release directory inside the MSVC.
Four, the first demo

Below we start to build our first demo, if the previous use of the VS2008 compiled gtest, then, we in VS2008, create a new Win32 Console application. Then you set up engineering properties, which are summarized as follows:

1. Set Gtest header file path

2. Set the Gtest.lib path

3.Runtime Library Settings

If it is release version, the Runtime library is set to/MT. Of course, you can also choose dynamic Link (/MD), if you have previously compiled gtest also use the same/MD option.

After the project is set up, we will write a simplest test case to try, we first write a tested function: int Foo (int a, int b)
{
if (a = = 0 | | b = = 0)
{
Throw "Don ' t do";
}
int C = a% B;
if (c = = 0)
return b;
Return Foo (b, c);
}

Yes, the above function is used to ask for GCD. Here we will write a simple test case. #include < gtest/gtest.h >

TEST (Footest, Handlenonezeroinput)
{
Expect_eq (2, Foo (4, 10));
Expect_eq (6, Foo (30, 18));
}

You can see how simple it is to write a test case. We used the macro with test, which has two parameters, and the official explanation for these two arguments is: [Testcasename,testname], and my definition of these two parameters is: [Testsuitename,testcasename], In the next article we'll see why this definition is so.

Checking the checkpoint, we use the EXPECT_EQ macro, which compares two numbers to be equal. Google also wraps a series of expect_* and assert_* macros, and the difference between the expect series and the Assert series is:

1. When the expect_* fails, the case continues to execute.

2. When the assert_* fails, it is returned directly in the current function, and the statement after assert_* in the current function will not execute.

In the next article, we'll discuss these assertion macros in detail. To get our case running, we also need to add the following code to the main function: int _tmain (int argc, _TCHAR * argv[])
{
Testing::initgoogletest (& argc, argv);
return run_all_tests ();
}

"Testing::initgoogletest (&ARGC, argv);": Gtest test Case allows you to receive a series of command-line arguments, so we pass command-line arguments to gtest for some initialization. The gtest command line arguments are very rich, and we'll learn more about them later.

"Run_all_tests ()": Run all Test Cases

OK, everything is ready, we run the case directly (a green, very cool):


v. Summary

This article is really very elementary, the purpose is to let never contact Gtest students understand gtest most basic use. Gtest There are many more advanced usage methods that we will discuss later. Summarize the contents of this article:

1. Use vs to compile Gtest.lib files

2. Set the properties of the test project (header file, lib file,/mt parameter (and use the same parameter when compiling gtest))

3. Use the test macro to start a testing case and use the Expect_*,asser_* series to set up checkpoints.

4. Initialize the environment in the main function, and then run the test case using the Run_all_test () macro.

Advantages:

1. Our test case itself is an EXE project, after compiling can be directly run, very convenient.

2. Writing test cases is very simple (with some simple macros such as test), so let's spend more effort on case design and writing.

3. Provides a powerful and rich assertion of the macros used for inspection of different checkpoints.

4. Improve the rich command line parameters to the case run a series of settings.


Google Open source C + + unit Test framework Google Test series (gtest) bis-Assertion First, the preface

This article mainly summarizes all the assertion-related macros in Gtest. In Gtest, the asserted macro can be understood as divided into two categories, one is the Assert series, the other is the expect series. An intuitive explanation is:

1. The assertion of the Assert_* series exits the current function (note: Not exiting the current case) when the checkpoint fails.

2. The assertion of the Expect_* series continues to proceed as the checkpoint fails. Second, the example

int type comparison, expected value: 3, Actual value: Add (1, 2)
Expect_eq (3, ADD (1, 2))
//

If your ADD (1, 2) result is 4, it will be output in the result: G:\myproject\c + + \gtestdemo\gtestdemo\gtestdemo.cpp: Error:value of:add (1, 2)
Actual:4
Expected:3

If you output the result to XML, the output will be: (for the output of the result as XML, see: http://www.cnblogs.com/coderzh/archive/2009/04/10/1432789.html)

< testcase name = "Demo" status = "Run" time = "0" classname = "Addtest" >
< failure message = "Value of:add (1, 2) actual:4expected:3" type = "" > <! [Cdata[g:\myproject\c++\gtestdemo\gtestdemo\gtestdemo.cpp:16
Value Of:add (1, 2)
Actual:4
Expected:3]]> </Failure >
</testcase >

If you are not satisfied with the automatic output error information, you can also use the operator << to put some custom information output, usually, this is useful for debugging or additional instructions for some checkpoints.

Here's an example:

If you do not customize the output using the << operator:
for (int i = 0; i < x.size (); + + i)
{
Expect_eq (X[i], y[i]);
}


See the results will be like this, you do not know the error I equals a few:
G:\myproject\c + + \gtestdemo\gtestdemo\gtestdemo.cpp: Error:value of:y[i]
Actual:4
Expected:x[i]
Which Is:3

If you use the << operator to export some important information:
for (int i = 0; i < x.size (); + + i)
{
Expect_eq (X[i], y[i]) << "Vectors x and y differ at index" << i;
}


From the output, you can navigate to an error occurred at i = 2 o'clock. This output looks more useful and easy to understand: G:\myproject\c + + \gtestdemo\gtestdemo\gtestdemo.cpp: Error:value of:y[i]
Actual:4
Expected:x[i]
Which Is:3
Vectors x and&nbnbsp;y differ at index 2

Triple, Boolean check

Fatal Assertion Nonfatal Assertion Verifies
Assert_true (condition); Expect_true (condition); Condition is true
Assert_false (condition); Expect_false (condition); Condition is False

iv. Numerical data-checking

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

Five, string check

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

*streq* and *strne* support both char* and wchar_t* types, *strcaseeq* and *strcasene* only receive char*, which is not commonly used. Here are a few examples: TEST (stringcmptest, Demo)
{
char * Pszcoderzh = "Coderzh";
wchar_t * Wszcoderzh = L "Coderzh";
std:: string strcoderzh = "Coderzh";
std::wstring Wstrcoderzh = L "Coderzh";

Expect_streq ("Coderzh", Pszcoderzh);
Expect_streq (L "Coderzh", Wszcoderzh);

Expect_strne ("Cnblogs", Pszcoderzh);
Expect_strne (L "Cnblogs", Wszcoderzh);

Expect_strcaseeq ("Coderzh", Pszcoderzh);
Expect_strcaseeq (L "Coderzh", Wszcoderzh); does not support

Expect_streq ("Coderzh", Strcoderzh.c_str ());
Expect_streq (L "Coderzh", Wstrcoderzh.c_str ());
}

VI. Show return success or failure

Direct return success: Succeed ();

Failed to return:

Fatal Assertion Nonfatal Assertion
FAIL (); Add_failure ();

TEST (Explicittest, Demo)
{
Add_failure () << "Sorry"; None Fatal Asserton, continue down execution.

FAIL (); Fatal assertion, do not proceed down the case.

Succeed ();
}

Vii. Abnormal inspection

Fatal Assertion Nonfatal Assertion Verifies
Assert_throw (statement, Exception_type); Expect_throw (statement, Exception_type); Statement throws an exception of the given type
Assert_any_throw (statement); Expect_any_throw (statement); Statement throws a exception of any type
Assert_no_throw (statement); Expect_no_throw (statement); Statement doesn ' t throw any exception

Example: int Foo (int a, int b)
{
if (a = = 0 | | b = = 0)
{
Throw "Don ' t do";
}
int C = a% B;
if (c = = 0)
return b;
Return Foo (b, c);
}

TEST (Footest, Handlezeroinput)
{
Expect_any_throw (Foo (10, 0));
Expect_throw (Foo (0, 5), char *);
}

Eight, predicate assertions

When using Expect_true or assert_true, sometimes you want to be able to output more detailed information, such as checking whether a function's return value is true or false, and want to be able to output what the incoming parameter is so that it can be traced after the failure. Therefore, the following assertions are provided:

Fatal Assertion Nonfatal Assertion Verifies
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
... ... ...

Google said that they only provide <=5 parameters, if you need to test more parameters, tell them directly. Let's see how this thing is used.
BOOL Mutuallyprime (int m, int n)
{
Return Foo (M, n) > 1;
}

TEST (Predicateassertiontest, Demo)
{
int m = 5, n = 6;
Expect_pred2 (Mutuallyprime, M, N);
}

When a failure occurs, an error message is returned:

Error:mutuallyprime (M, N) evaluates to False, where
M evaluates to 5
N evaluates to 6

If you are not satisfied with such an output, you can also customize the output format by using the following:

Fatal Assertion Nonfatal Assertion Verifies
ASSERT_PRED_FORMAT1 (PRED_FORMAT1, val1); ' EXPECT_PRED_FORMAT1 (PRED_FORMAT1, val1); PRED_FORMAT1 (VAL1) is successful
ASSERT_PRED_FORMAT2 (PRED_FORMAT2, Val1, val2); EXPECT_PRED_FORMAT2 (PRED_FORMAT2, Val1, val2); PRED_FORMAT2 (Val1, val2) is successful
... ...

Usage Example: t

Related Article

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.