google test 学习笔记1-google test primer.md

content
[TOC]

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:
1. Tests should be independent and repeatable. It’s a pain to debug a test that succeeds or fails as a result of other tests. Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging.
1. Tests should be well organized and reflect the structure of the tested code. Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base.
1. Tests should be portable and reusable. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral. Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations. (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.)
1. When tests fail, they should provide as much information about the problem as possible. Google C++ Testing Framework doesn’t stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle.
1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test content. Google C++ Testing Framework automatically keeps track of all tests defined, and doesn’t require the user to enumerate them in order to run them.
1. Tests should be fast. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other.

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.

Setting up a New Test Project

配置一个测试工程

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 (deprecated) and CMakeLists.txt for CMake (recommended) 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).
使用gtest 做单元测试,首先要把google test的源码编译成二进制,google提供一些流行的编译系统

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.

Basic Concepts

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.如果一个case里的多个测试需要共享数组,需要使用:test fixture

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.

Assertions

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.(ASSERT_*会结束current function, but EXPECT_*则不会, 它允许多个failure产生,推荐使用EXPECT,但是如果断言失败再执行后面的程序变得毫无意义的话,就用ASSERT)

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.

由于ASSERT_*会立即从当前函数返回,这样可能会跳过后面的clean-up code,这样就可能会引起内存泄露,这可能需要修复也可能不需要—-取决于泄露的类型,只要自己心里清楚是ASSERT_*引起的就行;
ASSERT_*的立即返回,是从被测试代码中立即返回,还是这个测试用例就结束了?–>答案是:并不一定会结束当前的TEST,只是这个失败的ASSERT函数返回,如果这个ASSERT是最外层的,那么就导致了这个测试用例的结束,如果它是子函数的话,那只会从子函数返回,并不会测试用例。(如果想要在ASSERT失败时结束测试用例,可考虑使用抛出方式)。

//自定义错误消息的简单示例,使用<<操作符
To provide a custom failure message, simply stream it into the macro using the << operator, or a sequence of such operators. An example:

ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are 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;
}

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.

任何C字符串和ostream都可以被用作assertion的custom message,特别是C string 和
std::string,如果是一个宽字符wchar_t或std::wstring,也可以被输出,但是会被转换成
utf-8格式打印

Basic Assertions

(这一节是基本断言,也就是比较条件是否为真)
These assertions do basic true/false condition testing.

Fatal assertionNonfatal assertionVerifies
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.

记住,ASSERT_*会结束current function, 但是EXPECT_*则不会,而是会继续下面的代码执行。
ASSERTION 失败意味着包含这个断言的TEST CASE也失败了。

Availability: Linux, Windows, Mac.

Binary Comparison

(这一个section描述了如何比较两个值)
This section describes assertions that compare two values.

Fatal assertionNonfatal assertionVerifies
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

(一旦失败,GT(google test) 会打印_val1 and 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.

注意,ASSERT_EQ 类及其相似的宏,应该把我们想要测试的表达式入在 actual 的位置, 把这个表达式的期望的输出入在 expected 的位置上,不能放反了。不然表达式可能会被当做字符串处理。

Value arguments must be comparable by the assertion’s comparison operator or you’ll get a compiler errorVal1 and val2一定要是可以比较的,不然会编译错误。). We used to require the arguments to support the << operator for streaming to an ostream, but it’s no longer necessary since v1.6.0 (if << is supported, it will be called to print the arguments when the assertion fails; otherwise Google Test will attempt to print them in the best way it can(在v1.6.0之前,gtest要求 val1Val2自己要支持”<<”操作,以便测试失败时gtest打印出错信息,但是现在不需要了,一旦出错,gtest会自己决定如何打印这个出错信息。). For more details and how to customize the printing of the arguments, see this Google Mock recipe.). 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.
(val1val2也可以是用户自定义的类型,但是这个类型得自己支持比较操作(>,<,==),在比较这些自定义类型时,推荐使用ASSERT_*, 因为一旦出错,可以打印出错结果及两个操作数。)

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.(参数只会被计算一次,考虑到有side effects 和 参数的解析顺序不同(依赖于编译器),所以你的参数要注意不要依赖于一种特殊或特定的解析顺序)

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.(ASSERT_EQ()是一个指针的工作方式,如果比较两个”C string”,它比较的是两个”C string”的地址是否相同,而不是值,如果要比较两个”C string”的值是否相同,要用ASSERT_STREQ(),比如ASSERT_STREQ(NULL, “C string”),如果是string的话,就要用ASSERT_EQ)

Macros in this section work with both narrow and wide string objects (string and wstring).(这一节的宏无论宽窄字符都支持比较)

注意,如果是C风格的字符串,比如char* 则要使用下一节介绍的 ASSERT_STREQ等来进行比较,但是如果是C++风格的字符串,就要使用本节介绍的ASSERT_EQ等来进行比较,而本节介绍的这些比较宏,都是支持宽窄字符的,比如:std::string和std::wstring。

Availability: Linux, Windows, Mac.

String Comparison

(这里是比较的C风格的字符串, 如果要比较std::string等,要使用上一节介绍的宏)
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 assertionNonfatal assertionVerifies
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.
(STREQ*, STRNE*也接受两个宽字符的比较,它们的值会被转换成utf-8打印)

A NULL pointer and an empty string are considered different.
(NULL跟空(“”)会被认为是不同的。)

Availability: Linux, Windows, Mac.

See also: For more string comparison tricks (substring, prefix, suffix, and regular expression matching, for example), see the Advanced Google Test Guide.

更多字符串比较的技巧(子串、前后缀及正则匹配)请参见 AdvancedGuide

Simple Tests

简单的例子
To create a test:
1. Use the TEST() macro to define and name a test function, These are ordinary C++ functions that don’t return a value.
1. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values.
1. The test’s result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds.如果这个TEST里面有一个错误,不管是ASSERT or EXPECT,或者是这个TEST崩溃了,都会导致整个TEST的失败

TEST(test_case_name, test_name) {
... test body ...
}

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. Both names must be valid C++ identifiers, and they should not contain underscore (_). 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.
TEST()的第一个参数是测试用例集合的名子,第二个参数是当前测试用例的名子,这两个名子的起名要符号C++变量的命名规则。一个测试用例集合可以有很多个测试用例,它们之间不能重名。但是不同测试用例集合的测试用例名可以重名

For example, let’s take a simple integer function:

int Factorial(int n); // Returns the factorial of n

A test case for this function might look like:

// 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));
}

//GT的结果依赖于test case名称,所以对同一模块的测试尽量用同一个test case name,
//这样在组织结果输出时就会输出到一起,看起来也直观
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.gtest测试结果的输出依赖于测试用例集合的名子,相同的测试用例集合的输出会在一起。也就是说,对同一模块或同一逻辑的测试,其测试集合的名子要相同,然后下面包含对这个模块不同方面的测试。

Availability: Linux, Windows, Mac.

Test Fixtures: Using the Same Data Configuration for Multiple Tests

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.
如果你的一个或多个测试使用的是相同的或相似的数据作为输入,那么可以使用text fixture,这样只用准备一次数据,然后多次重用来test

To create a fixture, just:
fixture使用步骤
1. Derive a class from ::testing::Test . Start its body with protected: or public: as we’ll want to access fixture members from sub-classes.testing::Test公开或保护继承出一个子类来
1. Inside the class, declare any objects you plan to use.子类中,声明需要使用的变量或对象
1. If necessary, write a default constructor or 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.如果需要,为该类写一个默认的构造函数(注意一定是默认的构造函数),或者使用SetUp()函数(注意首字母都是大写,不要写错了。一般都是重载一下这个函数),来准备数据,比如将需要使用的数据初始化等
//如果需要,去写一个析构函数或TearDown()函数去释放资源,至于到底该用哪一种,参见FAQ
1. If necessary, write a destructor or 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.如果需要,写一个析构函数或是使用TearDown()函数来释放资源**至于什么时候使用 constructor/deconstuctor什么时候使用SetUp()/TearDown()请看FAQ相关部分
1. If needed, define subroutines for your tests to share.如果需要,也可以在该类中定义一些子函数来完成需要的功能
When using a fixture, use TEST_F() instead of TEST() as it allows you to access objects and subroutines in the test fixture:
当使用fixture时,要使用TEST_F()

TEST_F(test_case_name, test_name) {
... test body ...
}

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.
TEST_F()的第一个参数,即测试用例集合的名字,必须要是刚才定义的类的名子

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“.
在使用TEST_F时,必须要先定义一个上面介绍的子类

For each test defined with TEST_F(), Google Test will:
1. Create a fresh test fixture at runtime
1. Immediately initialize it via SetUp() ,
1. Run the test
1. Clean up by calling TearDown()
1. Delete the test fixture.
Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests.

注意,在不同的TEST_F()运行时,虽然他们使用的是同一套数据,但是他们之间的数据互不干扰,也就是上一个TEST_F()的对某一个公有数据的修改,不会影响下一个TEST_F()的相同数据。可以理解成,TEST_F()们都保有这个类对象的一个实例。

As an example, let’s write tests for a FIFO queue class named Queue, which has the following interface:
下面用一个FIFO的Queue的例子来说明这种用法

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 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.

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 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:
1. Google Test constructs a QueueTest object (let’s call it t1 ).
1. t1.SetUp() initializes t1 .
1. The first test ( IsEmptyInitially ) runs on t1 .
1. t1.TearDown() cleans up after the test finishes.
1. t1 is destructed.
1. The above steps are repeated on another 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.

Invoking the Tests

调用这些测试
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.
TEST()TEST_F()暗中会自己注册到gtest,所以不像其他的C++ test框架,并不需要再把这些TEST()列举一遍来运行

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.
写完测试用例后,调用RUN_ALL_TESTS()宏来运行所有的TEST,这个函数返回0表示所有的TEST都运行成功了

When invoked, the RUN_ALL_TESTS() macro:
1. Saves the state of all Google Test flags.
1. Creates a test fixture object for the first test.
1. Initializes it via SetUp().
1. Runs the test on the fixture object.
1. Cleans up the fixture via TearDown().
1. Deletes the fixture.
1. Restores the state of all Google Test flags.
1. Repeats the above steps for the next test, until all tests have run.
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.

注意: 如果在TEST FIXTURE的构造或是SetUp()函数就出错了,那么后面的依赖于该类的测试也就变得没有意义了

Important: You must not ignore the return value of RUN_ALL_TESTS(), or gccwill 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().
你不应该忽略RUN_ALL_TESTS()的返回值(gcc会给出一个编译器错误),你不应该忽略RUN_ALL_TESTS()的返回值(gcc会给出一个编译器错误),这个合理的设计是因为:自动测试服务决定一个test是否通过是根据它的返回值判定的,而不是它在stdout/stderr里的输出,所以你的main()函数应该: return 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.

RUN_ALL_TESTS()只能被调用一次!

Availability: Linux, Windows, Mac.

Writing the main() Function

如何写main函数,你可以从这个样板文件开始写起
You can start from this boilerplate:

#include "this/package/foo.h"
#include "gtest/gtest.h"


namespace {


// The fixture for testing class Foo.
class FooTest : public ::testing::Test {
protected:
  // You can remove any or all of the following functions if its body
  // is empty.


  FooTest() {
    // You 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 are not enough for setting up
  // and cleaning up each test, you can define the following methods:


  virtual void SetUp() {
    // Code here will be called immediately after the constructor (right
    // before each test).
  }


  virtual void TearDown() {
    // Code here will be called immediately after each test (right
    // before the destructor).
  }


  // Objects declared here can be 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/package/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.
}


}  // namespace


int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

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.
InitGoogleTest()会解析命令行参数并赋值给gtest flags,会自动去掉那些不认识的flags,这允许用户自己定义gtest的行为通过各种各样的参数(参见AdvancedGuide.md)

You must call this function before calling RUN_ALL_TESTS(), or the flags won’t be properly initialized.
必须在RUN_ALL_TESTS()前被调用,否则gt flags可能不会被合理的初始化

On Windows, InitGoogleTest() also works with wide strings, so it can be used in programs compiled in UNICODE mode as well.
在windows下,InitGoogleTest()也支持宽字符,所以可以运行在UNICODE工程下

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.
你可能觉得在main()里花了较多的工作量,我们完全同意你的想法,所以我们在gtest/gtest_main.cc里面实现了一个默认的main函数,如果需要,你可以拷过去用。

Important note for Visual C++ users

对VC用户非常重要
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:

__declspec(dllexport) int PullInMyLibrary() { return 0; }

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:

int PullInMyLibrary();
static int dummy = PullInMyLibrary();

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!
上面写了这么长,其实就一点:不要把gtest代码写到lib or dll里面去,把直接放在exe里面。即:要与main在同一个模块里!

Where to Go from Here

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.
读到这里就读完了,你可以阅读samples.md去尝试写test了, 也可以去advancedguide.md里面,去学习更多有用的gtest 特性。

Known Limitations

已知的限制
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.
gtest在pthread下是线程安全的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值