The Google C + + unit testing Framework---advancedguide

Source: Internet
Author: User

This article is a translation of the Gtest Advanced Test guide, because the article is too long and is divided into two parts.

first, Introduction

This document will show you more assertions, as well as how to construct complex failure messages, propagate deadly failures, reuse and accelerate your test fixture, and use various flags in your TESTS.

second, more assertions

This section includes assertions that are less common but still important.

2.1 Explicit successes and failures

These three assertions do not actually test a value or Expression. instead, they produce success or failure directly. Similar to the macros that actually perform the tests, you can flow custom failure messages into Them.

Succeed ();  

The Build Succeeded. This does not make the overall test Successful. The test is considered successful only if the test does not have any assertion failures during its execution.

Note: succeed () is a pure documentary, and currently does not generate any user-visible Output. however, We may add succeed () messages to the output of Google test in the Future.

FAIL (); Add_failure (); Add_failure_at ("file_path", line_number);

Fail () produces fatal faults, while Add_failure () and add_failure_at () produce non-fatal Faults. These are useful when a control flow, rather than a Boolean expression, determines the success or failure of a test. For example, you might want to write as Follows:

Switch (expression) {case  1: ... some checks  ... Case 2: ... some other checks ...  Default:fail () << "We shouldn ' t get here.";}

Note: you can only use fail () in a function that returns VOID. For more information, see section assertion Placement.

2.2 Exception Assertion

These are used to verify that a piece of code throws (or does not throw) an exception of a given type:

fatal assertion nonfatal assertion verifi Es
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 an exception of any type
ASSERT_NO_THROW(Statement); EXPECT_NO_THROW(Statement); statement doesn ' t throw any exception

Examples:

Assert_throw (Foo (5), bar_exception); Expect_no_throw ({  int n = 5;  Bar (&n);});
III. predicate assertion for better error messages

While Google tests have a rich set of assertions, they can never be complete, because it's impossible (and not a good idea) to predict all the things users might encounter. therefore, sometimes users must use Expect_true () to check for complex expressions, because a better macro is missing. This has a problem that does not show the value of the part of your expression, making it difficult to understand what the error is. As a workaround, some users choose to construct their own failure messages and stream them to Expect_true (). however, This is embarrassing, especially when expressions have side effects or are expensive to Evaluate.

Google testing offers three different options to solve this problem:

3.1 Using the existing Boolean function

If you already have a function or function that returns a bool (or a type that can be implicitly converted to bool), you can use it in predicate assertions to get free printing of function parameters:

fatal assertion nonfatal Asser tion 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

above, Predn is an n-ary predicate function or functor, where val1,val2, ... And Valn are its parameters. If the predicate returns True when applied to a given parameter, the assertion succeeds or fails. When an assertion fails, it prints the value of each parameter. In either case, the parameter is evaluated only ONCE.

Here's an example:

Returns true iff m and n have no common divisors except 1.bool mutuallyprime (int m, int N) {...} const int a = 3;const int b = 4;const int c = 10;

Assert Expect_pred2 (Mutual prime,a,b); Will succeed while asserting Expect_pred2 (mutuallyprime,b,c); Will Fail.

! Mutuallyprime (b, C) is false, Whereb was 4c is 10

Attention:

1. If you see a compiler error when using assert_pred * or expect_pred * "nomatchingfunction to call (no matching functions called)", please see this FAQ for how to resolve it.
2. Currently we only provide predicate assertions for arity <= 5. If you need more advanced assertions, let us know.

3.2 Using a function that returns Assertionresult

Although expect_pred * () and friends are convenient for quick work, The syntax is unsatisfactory: you have to use different macros for different arities, and it feels more like Lisp than C + +. :: testing:: the Assertionresult class solves this Problem.

The Assertionresult object represents the result of the assertion (whether it is a success or failure, and the associated message). You can create assertionresult using one of the following factory functions:

Namespace testing {//Returns an Assertionresult object to indicate, an assertion Has//succeeded. Assertionresult assertionsuccess ();//Returns An Assertionresult object to indicate, that's an assertion Has//failed. Assertionresult assertionfailure ();}

You can then use the << operator to stream messages to the Assertionresult Object.

To provide more readable messages in a Boolean assertion (for example, expect_true ()), Write a predicate function that returns assertionresult instead of Bool. For example, If you define IsEven () as:

:: Testing::assertionresult IsEven (int n) {  if ((n% 2) = = 0)    return:: testing::assertionsuccess ();  else    return:: testing::assertionfailure () << n << "is odd";}

Instead of:

BOOL IsEven (int N) {  return (n% 2) = = 0;}

  The failed assertion would EXPECT_TRUE(IsEven(Fib(4))) Print:

Value of:iseven (Fib (4)) actual:false (odd*) expected:true

Instead of a more opaque:

Value Of:iseven (Fib (4)) Actual:falseExpected:true

  If you want to see messages that provide information in expect false and assert_false, and if the predicate slows down successfully, You can provide a success message:

:: Testing::assertionresult IsEven (int n) {  if ((n% 2) = = 0)    return:: testing::assertionsuccess () << n <& Lt "is even";  else    return:: testing::assertionfailure () << n << "is odd";}

 Then the statement would EXPECT_FALSE(IsEven(Fib(6))) print

Value of:iseven (Fib (6)) actual:true (8 is Even) expected:false
3.3 Using predicates to format

If you find by (ASSERT | EXPECT) _pred * and (ASSERT | EXPECT) _ (TRUE | FALSE) The default message generated is unsatisfactory, or some parameters of your predicate do not support streaming to ostream, you can use the following Predicate-formatter assertion to fully customize the formatting of the message:

fatal assertion nonfatal Asser tion verifies
Assert_pred_format 1 ( 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
... ... ...

The difference between this and the first two groups of macros is that it is not a predicate, (ASSERT | EXPECT) _pred_format * takes a predicate formatter (pred_formatn), which is a function or function signature:

:: Testing::assertionresult predicateformattern (const char*expr1, const char*expr2, ... const char*exprn, t1val1, T2val2 , ... tnvaln);
Iv. floating-point comparisons

Comparing floating-point numbers is Tricky. Due to rounding errors, two floats are unlikely to match exactly. therefore, the naïve comparison of Assert_eq usually does not Work. And because floating-point can have a wide range of values, there is no single fixed error limit Working. It is best to compare a fixed relative error boundary, except for a value close to 0 due to the loss of Precision.

In general, for floating point comparisons, users need to carefully select the error BOUNDS. If they don't want or care, comparisons based on units in the last location (ULP) are a good default, and Google testing provides assertions to do This. Full details about ULP are quite long; If you want to learn more, please see this article about floating comparisons this article on float Comparison.

Floating-point Macros
Fatal Assertion Nonfatal Assertion verifies
ASSERT_FLOAT_EQ(val1, Val2); EXPECT_FLOAT_EQ(val1, Val2); The float values are almost equal
ASSERT_DOUBLE_EQ(val1, Val2); EXPECT_DOUBLE_EQ(val1, Val2); The double values are almost equal

"almost equal" means that two values are within 4 ULP of each other.

The following assertions allow you to select acceptable error limits:

Fatal Assertion Nonfatal Assertion verifies
ASSERT_NEAR(val1, val2, Abs_error); EXPECT_NEAR(val1, val2, Abs_error); The difference between val1 and val2 doesn ' t exceed the given absolute error

。。。。 Too much to see when you need it.

V. Windows HRESULT Assertion

These assertions test the HRESULT for success or Failure.

Fatal Assertion Nonfatal Assertion verifies
ASSERT_HRESULT_SUCCEEDED(Expression); EXPECT_HRESULT_SUCCEEDED(Expression); expression is a successHRESULT
ASSERT_HRESULT_FAILED(Expression); EXPECT_HRESULT_FAILED(Expression); expression is a failureHRESULT

The generated output contains a human-readable error message associated with the HRESULT code returned by Expression.

You might use them like this:

CComPtr shell; assert_hresult_succeeded (shell. CoCreateInstance (L "shell.application")); CComVariant empty; assert_hresult_succeeded (shell->shellexecute (ccombstr (url), empty, empty, empty, empty));
Vi. Type Assertion

:: testing::staticasserttypeeq<t1, t2> ();

You can call this function to claim that the assertion type T1 and T2 are the Same. If the assertion is satisfied, the function does not take any Action. If the type is different, the function call will not compile, and the compiler error message (depending on the compiler) will display the actual values of T1 and T2. This is primarily useful in template code .

Note: when used in a class template or function template member function, Staticasserttypeeq <T1,T2> () is only valid when the function is Instantiated. For example, Given:

Template <typename t> class Foo {public:  void Bar () {:: testing::staticasserttypeeq<int, t> ();}};

The Code:

void Test1 () {foo<bool> Foo;}

Compiler errors will not be generated because Foo <bool>:: Bar () is never actually instantiated. instead, you need to:

void Test2 () {foo<bool> foo; foo. Bar (); }

Causes a compiler Error.

Vii. Assertion Placement (assertion Placement)

You can use assertions in any C + + Function. In particular, it does not have to be a method of testing fixture Classes. One constraint is that assertions that generate fatal failures (fail * and Assert_ *) can only be used in void return functions . This is the result of Google testing not using Exceptions. If you put it in a non-void function, you get a confusing compilation error, such as "error:void value not ignored as it ought to be".

If you need to use assertions in a function that returns non-void, an option is to have the function return the value in the Out Parameter. For example, you can override T2 foo (T1 x) to void foo (T1 x,t2 * result). You need to make sure that * result contains some reasonable values even if the function returns PREMATURELY. Since the function now returns void, you can use any assertion inside it.

If changing the type of a function is not an option, you should use assertions that generate non-fatal failures, such as Add_failure * and Expect_ *.

note: Constructors and destructors are not treated as void return functions according to the C + + language specification, so you cannot use fatal assertions in Them. If you try, you will get a compilation Error. A simple workaround is to transfer the entire body of a constructor or destructor to a private void return method. however, you should be aware that the failure of the fatal assertion in the constructor does not terminate the current test, as your intuition implies; It only returns early from the constructor, possibly leaving your object in a partially constructed State. similarly, a fatal assertion failure in a destructor may cause your object to be in a partially corrupted State. Use assertions carefully in these cases!

Viii. teaching Google testing how to print your values

When a test claim (such as Expect_eq) fails, Google test prints the parameter values to help you Debug. It uses a user-extensible value printer.

This printer knows how to print built-in C + + types, native arrays, STL containers, and any type of support << Operator. For other types, It prints the raw bytes in the value and expects the user to be able to calculate it.

As mentioned earlier, the printer is Extensible. This means that you can teach it to do a better job of printing your specific type instead of dumping Bytes. To do this, define << your type:

#include <iostream>namespace foo {class Bar {...};  We want Google Test to being able to print instances of This.//It's important that the << operator are defined in th E same//namespace that defines Bar.  C + + ' s look-up rules rely on that.::std::ostream& operator<< (::std::ostream& os, const bar& Bar) {  R Eturn OS << bar. Debugstring ();  Whatever needed to print bar to os}}  //namespace foo

sometimes, This may not be an option: your team might think its bad style has a bar of << operator, or bar may already have a << operator, not doing what you want (you can't change it). If so, you can define a printto () function as Follows:

#include <iostream>namespace foo {class Bar {...};//It ' s important that printto () are defined in the SAME//NAMESP Ace that defines Bar.  C + + ' s look-up rules rely on that.void printto (const bar& bar,:: std::ostream* os) {  *os << bar. Debugstring ();  Whatever needed to print bar to os}}  //namespace foo

If you have defined << and Printto (), The latter will be used during Google Testing. This allows you to customize how values are displayed in the output of Google tests without affecting the code that relies on the behavior of its << Operators.

If you want to use Google Test's value printer to print a value of x yourself, simply call:: testing:: printtostring (x), which returns an std:: string:

vector<pair<bar, int> > bar_ints = Getbarintvector (); Expect_true (iscorrectbarintvector (bar_ints))    << "bar_ints =" <<:: Testing::P rinttostring (bar_ints) ;
Extending Google test by handling test Events

This is quite complicated, written in a separate document ...

Reprint Please specify source: http://www.cnblogs.com/jycboy/p/gtest_AdvancedGuide.html

The Google C + + unit testing Framework---advancedguide

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.