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

ProtoBuf编译生成Google.Protobuf.dll与Protoc.exe、自定义生成代码规则 是一种可以将自定义的结构体序列化(反序列化)成字符流(byte[])的中间工具。对比JsonXML二进制,在序列化速度上更快,占用内存上更小,但相对而言操作更麻烦。由于Proto工具提供的语言支持,支持用户可以在不同的语言中对同样数据结构进行序列化和反序列化。本文目的下载Protobuf开源库,编译生成使用C#语言序列化和反序列化对应所需的dll(Google.Protobuf.dll)和应用程序(protoc.exe) 阅读详情

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 error(Val1 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要求 val1和Val2自己要支持”<<”操作,以便测试失败时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.
(val1和val2也可以是用户自定义的类型,但是这个类型得自己支持比较操作(>,<,==),在比较这些自定义类型时,推荐使用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下是线程安全的

Sinutrain下载安装与开启OPC UA---kalrry Sinutrain 开启 OPC UA 本教程只适用于版本,其他版本配置目录有所改变建议安装到默认路径,否则后期修改路径时候容易忽略细节本教程提供安装包为官方包,网上有些非官方包安装后容易出现授权问题,比如授权管理器无法启动,官方技术会建议你重装系统,很多时候是因为安装包非官方包在首次安装前,建议重启一遍系统。 阅读详情

相关推荐

C#集成Bartender:动态图片标签打印的实战与优化

本文详细介绍了在C#程序中集成Bartender实现动态图片标签打印的实战方法与优化策略。通过具名数据源绑定、图片对象尺寸控制等核心技巧,解决了动态图片显示/隐藏的难题,并提供了从模板设计、代码架构到性能优化、错误处理的全流程指南,帮助开发者构建稳定高效的工业级标签打印系统。

weixin_29216957的博客 431

Googletest Primer

Googletest Primer 原文地址:https://github.com/google/googletest/blob/master/googletest/docs/primer.md Introduction: Why googletest? googletest helps you write better C++ tests. googletest is a testing fra...

weixin_30409849的博客 729

Windows系统的Mamba环境配置详细教程(状态空间模型)

causal_conv1d也是安装mamba的依赖必须库。安装完成后,通过pip list可以查看到安装的库。Triton是安装mamba的依赖,需要先安装。上述工作准备好后,按下面步骤安装。直接根据离线文件安装即可。是自己的虚拟环境名字。

2301_77831163的博客 3674

protobuf linux 编译 动态库

直接cmake.. 可能会报Cannot find third_party/googletest directory that's needed to build tests.错误,缺少该测试框架的依赖。可以选择修改CMakeLists.txt不使用该功能, 把 “Build tests”置为OFF。版本:v3.13.0, 其他版本如果cmake目录结构相同,方法类似。cmake目录下mkdir build创建build文件。cmake ..成功后直接make即可编译。

qq_31841023的博客 1277

使用DDR4控制器实现多通道数据读写

这种高带宽对于大量的数据的应用非常重要。对于Controller/PHY Mode 的选择,我们使用Controller + PHY模式,Xilinx UltraScale/UltraScale+等高端FPGA通常包含硬核PHY,选择Controller + PHY模式可直接利用硬核,降低功耗和延迟,并且此模式的开发更易上手。在Basic页面下,首先勾选上AXI4 Interface选项,我们选用的内存接口速度为2133MHz的ddr4芯片,由于双沿触发,频率为1066MHz,那么周期应为938ps。

weixin_38828382的博客 1363

python轮胎缺陷检测_基于深度学习的轮胎缺陷无损检测与分类技术研究

基于深度学习的轮胎缺陷无损检测与分类技术研究【摘要】:随着汽车行业快速发展及汽车保有量的持续增长,大大增加了对轮胎的需求,而轮胎质量在很大程度上决定了轮胎的使用寿命,也是在行驶过程中对人们生命财产安全的保障,同时对轮胎进行在线质量检测也便于轮胎生产企业及时发现生产线中存在的不合格产品,以此来调整机械设备甚至轮胎的生产工艺,避免造成生产材料的浪费。因此,检测轮胎质量是轮胎生产过程中必不可缺少的一部分...

weixin_39689428的博客 1424

Android studio第一次打开遇到的问题

作为超级新手,今天第一次安装好打开android studio,发现如下问题: Entry fileTemplates//code/Google Test Fixture SetUp Method.cc.ft not found in C:/Program Files/Android/Android Studio/lib/idea.jar 然后,在优快云里搜到了相关解决办法,原方法见 https...

qq_41415956的博客 4724

C#粘包和分包问题及解决方法

一:通过图解法来描述一下分包和粘包,这样客户更清晰直观的了解:  下面对上面的图进行解释:  1.正常情况:如果Socket Client 发送的数据包,在Socket Server端也是一个一个完整接收的,那个就不会出现粘包和分包情况,数据正常读取。  2.粘包情况:Socket Client发送的数据包,在客户端发送和服务器接收的情况下都有可能发送,因为客户端发送的数据都是发送的一个缓冲...

weixin_42033401的博客 7767

Weex Core 中的 Google Test(googletest 1.9)C++ 单元测试框架集成指南

Google Test 是 Google 出品的 C++ 测试框架,在 Weex 开源仓库中作为 `weex_core` 原生核心的单元测试基础组件被完整托管。本文以仓库内 [googletest README](https://link.gitcode.com/i/691ae6ec5ba7c357d18454af7f6eb64f) 为骨架,结合 [WeexCoreTest](https://li

gitblog_00087的博客 541

Python爬虫实战:利用Playwright与异步技术高效抓取链家十万级二手房数据

在开始编写代码之前,我们首先需要为项目选择合适的技术栈。1. 传统方案:Requests + BeautifulSoup优点: 简单、轻量、学习成本低。直接发送HTTP请求获取HTML,然后解析。缺点: 对于大量由JavaScript动态渲染的内容无能为力。现代网站(包括链家)大量使用JS来加载数据和实现交互,简单的HTTP请求无法获取到完整的页面内容。此外,容易被基于IP或请求头特征的反爬机制拦截。2. 进阶方案:Selenium优点。

2201_76125261的博客 889

063、推挽变换器的磁偏问题与解决

本文针对推挽变换器中的磁偏问题展开分析。作者通过实际案例指出,磁偏主要由开关管导通压降差异和驱动信号不对称引起,会导致变压器饱和、MOS管炸毁等问题。文章提供了四种解决方案:采用电流模式控制、添加隔直电容、优化对称驱动设计以及引入磁芯气隙(作为最后手段)。调试时应重点观察原边电流波形对称性、变压器声音和直流分量。作者强调实践经验的重要性,建议预留隔直电容位置,并指出推挽拓扑在500W以上功率场合的局限性。这些基于实战的经验总结为电源工程师提供了有价值的参考。

Jack010169的博客 310

Google Test Primer 实战指南:在 miniblink49 仓库中用 gtest 编写 C++ 单元测试

Google Test(Google C++ Testing Framework)是 Chromium/V8 生态中事实标准的 C++ 单元测试框架,而 miniblink49 仓库的 [v8_7_5/testing/gtest](https://link.gitcode.com/i/2571955b040950121f2124175a1772ed) 目录中完整携带了其源码、文档与构建脚本,是仓库

gitblog_01124的博客 11

OpenClaw实战五|企业文档AI助理:对接内部知识库+自动答疑+文档生成,员工自助查资料零等待

企业最大的隐性成本,不是设备、不是房租,而是内部知识的混乱与流失。OpenClaw企业文档AI助理,本质是给企业做了一个7×24小时在线、永不疲倦、精准无误、自动更新的内部知识管家。它不替代HR、行政、IT,而是把他们从无穷无尽的重复问答、机械文档编写里解放出来,去做更有价值的管理、服务、优化工作。对中小企业来说,不用买昂贵的知识库系统、不用招开发、不用做复杂集成,一台私有化服务器,两天就能落地,性价比拉满。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 144

OmniVChat数据集结构全解析:从single_turn.jsonl到1080p媒体的13475条Rubric逐字段拆解

**OmniVChat** 是一个原生音视频对话评测数据集(OmniVChat-Bench):2800 段"边看边听"的对话、13475 条分层 Rubric 评分标准、3490 个 1080p 带音轨的 mp4。用户的问题不在文字里,而是说在视频的声音里。本文逐字段拆解 [data/single_turn.jsonl](https://link.gitcode.com/i/17cee1e91ff

gitblog_00966的博客 686

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

RNOH C++ 模块 Google Test 单元测试编写指南:不依赖鸿蒙设备的主机端 gtest 实战

本文面向 React Native 鸿蒙化仓库(ohos_react_native,即 RNOH)中所有 C++ 模块的测试编写者,系统讲解"不依赖鸿蒙设备、可在 macOS / Linux / Windows 主机上直接编译运行"的 Google Test(gtest)+ Google Mock(gmock)单元测试编写规范。全文以仓库中的技能文档 [.opencode/agent/gtest-

gitblog_00641的博客 829

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

Apache WeexCore 测试体系实战:基于 Google Test(googletest)的 C++ 单元测试框架集成指南

Google Test 是 Google 官方开源的 C++ 单元测试框架,在本仓库中它作为 Apache Weex 跨平台渲染内核(WeexCore)的测试基础设施被整体集成,负责驱动 `weex_core/test` 下的所有 C++ 单元测试。本文以仓库中 `weex_core/test/third_party/googletest/README.md` 为骨架,结合 WeexCore 实际

gitblog_01178的博客 224

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

BusTub 中的 GoogleTest Primer:从零掌握 C++ 单元测试框架(断言、TEST/TEST_F 与测试组织)

> 导读:本文以 GoogleTest 官方入门指南(Primer)为核心,系统讲解 GoogleTest 的测试理念、断言机制、`TEST()`/`TEST_F()` 宏、`RUN_ALL_TESTS()` 运行流程与 `main()` 编写方式,并结合 BusTub 数据库系统(Educational RDBMS)仓库中的真实测试代码(如 `test/common/rwlatch_test.c

gitblog_00290的博客 73

Apache Weex 中的 Google Test 构建与集成指南:从源码编译到 WeexCore CMake 测试体系

Google Test(gtest)是 WeexCore C++ 侧单元测试的底层支撑框架,其完整源码被 vendored 进当前仓库的 `weex_core/test/third_party/googletest` 目录,并由 `weex_core/test` 下的 CMake 工程直接引用。本文以官方 [googletest/README.md](https://link.gitcode.co

gitblog_00696的博客 15

Google Test Primer 详解:miniblink49 仓库内嵌 gtest 的 C++ 单元测试入门与实践

本文以 miniblink49 仓库内嵌的 Google C++ Testing Framework(Google Test)1.5 入门文档([v8_7_5/testing/gtest/docs/V1_5_Primer.md](https://link.gitcode.com/i/73d6f0af132a91fd8cb459f55162b063))为骨架,系统讲解从零搭建测试工程、编写断言、组织

gitblog_00161的博客 11

GoogleTest Primer 精读:基于 googletest 仓库掌握 C++ 单元测试的核心方法论与实战写法

本篇指南以仓库 [docs/primer.md](https://link.gitcode.com/i/24e686e97b233a5434bbbdbdfb58e34a) 为主体骨架,系统讲解 GoogleTest(Google Testing and Mocking Framework)的入门知识:从断言、`TEST()`/`TEST_F()` 宏、测试夹具与 `RUN_ALL_TESTS()`

gitblog_00957的博客 238

GoogleTest Primer 深入解读:gperftools 仓库内的 C++ 单元测试实践指南

本文以 gperftools 仓库中随附的 GoogleTest 入门文档([vendor/googletest/docs/primer.md](https://link.gitcode.com/i/be66f2c1a3cf1bd6b1f7eaf5c8307197))为主线,系统讲解 GoogleTest 的核心概念、断言体系、简单测试与 Test Fixture 的写法、测试入口与 main()

gitblog_00639的博客 848

osquery 单元测试编写与构建实战:从 example_test 到 CTest 全流程指南

osquery 将单元测试视为代码提交的质量门槛:每一个合入的改动都应附带可运行的测试。本文以 osquery 官方测试指南为主线,完整讲解如何从零编写、构建、注册并运行一个基于 Google Test 的单元测试,并深入 CMake 构建体系(`add_osquery_executable`、`add_test`、CTest)与测试辅助库(`tests_helper`)的源码实现,帮助你为任意

gitblog_01106的博客 150

Apache Weex 核心引擎测试基石:Google Mock(gMock)C++ 测试框架构建与实战指南

Google Mock(gMock)是 Google 出品的 C++ 模拟(mocking)框架,用于快速创建 mock 类、编写交互式单元测试,帮助开发者在隔离依赖的前提下验证模块间的调用契约。在 Apache Weex 仓库中,Google Mock 与 Google Test 一起以第三方源码形式内置于 `weex_core/test/third_party/googletest`,作为 W

gitblog_00260的博客 159

TEN-framework 中的 C++ 测试实战:googletest Primer 核心概念与断言体系全解析

本文以 [third_party/googletest/docs/Primer.md](https://link.gitcode.com/i/1e3c1199c913c19fc485842e3dbba4b0) 为主体骨架,系统讲解 googletest 测试框架的核心理念、术语体系、断言分类、`TEST()`/`TEST_F()` 用例组织方式、`RUN_ALL_TESTS()` 执行机制以及 `

gitblog_00317的博客 471

Apache Weex(Incubator)C++ 测试入门:基于 Googletest Primer 的断言、测试夹具与工程实践

本文以仓库内置的 Googletest 入门文档 [primer.md](https://link.gitcode.com/i/e1d83dd648cc228b6bbc58eec0fb94df) 为主体,系统讲解如何在 C++ 工程中使用 Googletest 编写单元测试:从断言宏的选择、`TEST()`/`TEST_F()` 的组织方式,到 `main()` 与 `RUN_ALL_TESTS(

gitblog_00369的博客 446

Apache Weex 内核测试基石:Google C++ Mocking Framework(Google Mock)入门实战指南

Google C++ Mocking Framework(简称 Google Mock)是构建在 Google Test 之上的 C++ 模拟(Mock)库,它通过少量宏即可生成 mock 类,并用近似自然语言的 `EXPECT_CALL()` 语法对"方法何时被调用、以什么参数调用、调用几次、返回什么"进行声明式校验。在 Apache Weex 的 C++ 内核中,[weex_core/test

gitblog_00733的博客 480
上一篇: float 转定点计算加法和乘法
下一篇: google test 学习笔记2-google test Advanced guide
beichen
博客等级 码龄16年 4粉丝 8原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值