Googletest Primer 官方机翻

Googletest Primer 官方机翻

Introduction: Why googletest?


googletest helps you write better C++ tests.

googletest is a testing framework developed by the Testing Technology team with Google’s specific requirements and constraints in mind. Whether you work on Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it supports any kind of tests, not just unit tests.

googletest是测试技术团队根据谷歌的具体要求和约束开发的一个测试框架。无论你是在Linux、Windows还是Mac上工作,只要你写的是c++代码,googletest都可以帮助你。它支持任何类型的测试,而不仅仅是单元测试。

So what makes a good test, and how does googletest fit in? We believe:

那么,什么是好的测试,googletest又是如何融入其中的呢?我们相信:

  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. googletest isolates the tests by running each of them on a different object. When a test fails, googletest allows you to run it in isolation for quick debugging.

测试应该是独立且可重复的。调试一个测试的成功或失败会影响到其他测试,这是一件痛苦的事情。Googletest通过在不同的对象上运行每个测试来隔离测试。当测试失败时,googletest允许你独立运行它以快速调试。

  1. Tests should be well organized and reflect the structure of the tested code. googletest groups related tests into test suites 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.

测试应该有良好的组织,并反映被测试代码的结构。Googletest将相关测试分组到可以共享数据和子程序的测试套件中。这种常见的模式很容易识别,也使测试易于维护。当人们切换项目并开始在一个新的代码基上工作时,这种一致性尤其有用。

  1. Tests should be portable and reusable. Google has a lot of code that is platform-neutral; its tests should also be platform-neutral. googletest works on different OSes, with different compilers, with or without exceptions, so googletest tests can work with a variety of configurations.

测试应该是便携式和可重复使用的。谷歌有很多与平台无关的代码;它的测试也应该与平台无关。googletest可以在不同的操作系统、不同的编译器上运行,有例外也有例外,所以googletest的测试可以在各种配置下运行。

  1. When tests fail, they should provide as much information about the problem as possible. googletest 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.

当测试失败时,应该尽可能多地提供有关问题的信息。Googletest不会因为第一次测试失败就停止。相反,它只是停止当前测试并继续进行下一个测试。还可以设置报告非致命故障的测试,在此之后当前测试将继续。因此,你可以在一个运行-编辑-编译循环中检测并修复多个bug。

  1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test content. googletest automatically keeps track of all tests defined, and doesn’t require the user to enumerate them in order to run them.

测试框架应该将测试编写者从家务活中解放出来,让他们专注于测试内容。Googletest自动跟踪所有定义的测试,并且不需要用户枚举它们来运行它们。

  1. Tests should be fast. With googletest, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other.

测试应该很快。使用googletest,你可以在不同测试之间重用共享资源,并且只需要支付一次设置/删除的费用,而不需要让测试相互依赖。

Since googletest 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!

由于googletest基于流行的xUnit架构,如果你之前使用过JUnit或PyUnit,你会觉得很舒服。如果没有,你需要大约10分钟的时间来学习基础知识并开始。所以让我们开始吧!

Beware of the nomenclature

注意命名法


Note:
There might be some confusion arising from different definitions of the terms Test, Test Case and Test Suite, so beware of misunderstanding these.
测试、测试用例和测试套件的不同定义可能会引起一些混淆,所以要注意这些误解。

Historically, googletest started to use the term Test Case for grouping related tests, whereas current publications, including International Software Testing Qualifications Board (ISTQB) materials and various textbooks on software quality, use the term Test Suite for this.

历史上,googletest开始使用术语Test Case来分组相关的测试,而当前的出版物,包括国际软件测试资格委员会(ISTQB)的材料和各种关于软件质量的教科书,都使用术语Test Suite来进行分组。

The related term Test, as it is used in googletest, corresponds to the term Test Case of ISTQB and others.

googletest中使用的相关术语测试,对应于ISTQB和其他的术语测试用例。

The term Test is commonly of broad enough sense, including ISTQB’s definition of Test Case, so it’s not much of a problem here. But the term Test Case as was used in Google Test is of contradictory sense and thus confusing.

术语测试通常具有足够广泛的意义,包括ISTQB对测试用例的定义,因此在这里它不是一个大问题。但是在谷歌测试中使用的测试用例是一个矛盾的概念,容易引起混淆。

googletest recently started replacing the term Test Case with Test Suite. The preferred API is TestSuite. The older TestCase API is being slowly deprecated and refactored away.

googletest最近开始用Test Suite替换Test Case这个术语。首选API是TestSuite。旧的TestCase API正在慢慢被弃用和重构。

So please be aware of the different definitions of the terms:

所以请注意这些术语的不同定义:

Meaninggoogletest TermISTQB Term
Exercise a particular program path with specific input values and verify the resultsTEST()Test Case
Meaninggoogletest TermISTQB Term
使用特定的输入值练习特定的程序路径,并验证结果TEST()Test Case

Basic Concepts


When using googletest, 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.

使用googletest时,首先要编写断言,即检查条件是否为真的语句。断言的结果可以是成功、非致命失败或致命失败。如果发生致命故障,则终止当前函数;否则程序继续正常运行。

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 suite contains one or many tests. You should group your tests into test suites that reflect the structure of the tested code. When multiple tests in a test suite need to share common objects and subroutines, you can put them into a test fixture class.

一个测试套件包含一个或多个测试。您应该将测试分组到反映被测试代码结构的测试套件中。当一个测试套件中的多个测试需要共享公共对象和子程序时,可以将它们放入一个测试夹具类中。

A test program can contain multiple test suites.

一个测试程序可以包含多个测试套件。

We’ll now explain how to write a test program, starting at the individual assertion level and building up to tests and test suites.

下面介绍如何编写测试程序,从单个断言开始,逐步构建测试和测试套件。

Assertions


googletest assertions are macros that resemble function calls. You test a class or function by making assertions about its behavior. When an assertion fails, googletest 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 googletest’s message.

Googletest的断言是类似于函数调用的宏。你可以通过断言来测试一个类或函数的行为。当断言失败时,googletest会打印出断言的源文件、行号位置以及失败消息。你也可以提供一个自定义的失败消息,它将被附加到googletest的消息中。

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 failure 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_*版本在失败时会产生致命错误,并中止当前函数。EXPECT_*版本会产生非致命错误,不会中止当前函数。通常使用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_*从当前函数立即返回,可能跳过后面的清理代码,因此可能会导致空间泄漏。根据泄漏的性质,它可能值得修复,也可能不值得修复——因此,如果您除了断言错误之外还遇到堆检查器错误,请记住这一点

To provide a custom failure message, simply stream it into the macro using the << operator or a sequence of such operators. See the following example, using the ASSERT_EQ and EXPECT_EQ macros to verify value equality:

要提供自定义的失败消息,只需使用<<操作符或一系列此类操作符将其流到宏中。请参阅下面的示例,使用ASSERT_EQEXPECT_EQ宏来验证值是否相等:

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.

任何可以流化为ostream的东西都可以流化为断言宏——特别是C字符串和字符串对象。如果一个宽字符串(wchar_t*、Windows上UNICODE模式下的TCHAR*std::wstring)被流式转换为断言,它在打印时将被转换为UTF-8。

GoogleTest provides a collection of assertions for verifying the behavior of your code in various ways. You can check Boolean conditions, compare values based on relational operators, verify string values, floating-point values, and much more. There are even assertions that enable you to verify more complex states by providing custom predicates. For the complete list of assertions provided by GoogleTest, see the Assertions Reference.

GoogleTest提供了一组断言,以各种方式验证代码的行为。你可以检查布尔条件,基于关系运算符比较值,验证字符串值、浮点值,等等。甚至还有一些断言可以通过提供自定义谓词来验证更复杂的状态。有关GoogleTest提供的断言的完整列表,请参阅断言参考

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.

使用TEST()宏来定义和命名一个测试函数。这些是没有返回值的普通c++函数。

  1. In this function, along with any valid C++ statements you want to include, use the various googletest assertions to check values.

在这个函数中,连同任何你想包含的有效c++语句,使用各种googletest断言来检查值。

  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(TestSuiteName, TestName) {
  ... test body ...
}

TEST() arguments go from general to specific. The first argument is the name of the test suite, and the second argument is the test’s name within the test suite. Both names must be valid C++ identifiers, and they should not contain any underscores (_). A test’s full name consists of its containing test suite and its individual name. Tests from different test suites can have the same individual name.

TEST()的参数从通用变为具体。第一个参数是测试套件的名称,第二个参数是测试套件中的测试名称。这两个名字都必须是有效的c++标识符,而且不能包含下划线(_)。测试的全名由包含它的测试套件和它的单个名称组成。来自不同测试套件的测试_可以具有相同的单个名称

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

举个例子,让我们来看一个简单的integer函数:

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

A test suite for this function might look like:

// Tests factorial of 0.
TEST(FactorialTest, HandlesZeroInput) {
  EXPECT_EQ(Factorial(0), 1);
}

// Tests factorial of positive numbers.
TEST(FactorialTest, HandlesPositiveInput) {
  EXPECT_EQ(Factorial(1), 1);
  EXPECT_EQ(Factorial(2), 2);
  EXPECT_EQ(Factorial(3), 6);
  EXPECT_EQ(Factorial(8), 40320);
}

googletest groups the test results by test suites, so logically related tests should be in the same test suite; 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 suite FactorialTest.

Googletest将测试结果按测试套件分组,因此逻辑上相关的测试应该在同一个测试套件中;换句话说,它们的TEST()第一个参数应该是相同的。在上面的例子中,我们有两个测试,HandlesZeroInput和HandlesPositiveInput,它们属于同一个测试套件FactorialTest

When naming your test suites and tests, you should follow the same convention as for naming functions and classes.

当命名你的测试套件和测试时,你应该遵循与命名函数和类相同的约定

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. This allows you to reuse the same configuration of objects for several different tests.

如果要编写两个或多个对类似数据进行操作的测试,可以使用测试夹具(test fixture)。这允许您在多个不同的测试中重用相同的对象配置。

To create a fixture: 创建一个 fixture

  1. Derive a class from ::testing::Test . Start its body with protected:, as we’ll want to access fixture members from sub-classes.

从::testing::Test派生一个类。以protected:开头,因为我们希望访问子类中的fixture成员。

  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 - Use override in C++11 to make sure you spelled it correctly.

如果有必要,编写一个默认构造函数或SetUp()函数来为每个测试准备对象。一个常见的错误是将SetUp()拼写为SetUp()并加上一个小u -请在c++ 11中使用覆盖函数来确保拼写正确

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

如果有必要,编写析构函数或 TearDown() 函数来释放在 SetUp() 中分配的所有资源。要了解什么时候应该使用构造函数/析构函数,什么时候应该使用_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(),因为它允许你访问测试夹具中的对象和子程序:

TEST_F(TestFixtureClassName, TestName) {
  ... test body ...
}

Unlike TEST(), in TEST_F() the first argument must be the name of the test fixture class. (_F stands for “Fixture”). No test suite name is specified for this macro.

TEST()不同,在TEST_F()中,第一个参数必须是测试夹具类的名称。(_F表示“Fixture”)。没有为此宏指定测试套件名称。

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.

不幸的是,**c++宏系统不允许我们创建一个宏来处理这两种类型的测试。**使用错误的宏会导致编译器错误。

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()中使用它之前先定义一个测试夹具类,**否则编译器会报错“virtual outside class declaration”。

For each test defined with TEST_F(), googletest will create a fresh test fixture at runtime, immediately initialize it via SetUp(), run the test, clean up by calling TearDown(), and then delete the test fixture. Note that different tests in the same test suite have different test fixture objects, and googletest always deletes a test fixture before it creates the next one. googletest 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()定义的测试,googletest将在运行时创建一个新的测试夹具,立即通过**SetUp()初始化它,运行测试,通过调用TearDown()**进行清理,然后删除测试夹具。注意,同一个测试套件中的不同测试具有不同的测试夹具对象,而且googletest总是在创建下一个测试夹具之前删除一个测试夹具Googletest不会在多个测试中重用同一个测试夹具。 一个测试对fixture所做的任何更改都不会影响其他测试。

As an example, let’s write tests for a FIFO queue class named Queue, which has the following interface:

举个例子,让我们为一个名为queue的FIFO队列类编写测试,它有如下接口:

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.

首先,定义一个fixture类。按照惯例,应该将其命名为FooTest,其中Foo是要测试的类。

class QueueTest : public ::testing::Test {
 protected:
  void SetUp() override {
     // q0_ remains empty
     q1_.Enqueue(1);
     q2_.Enqueue(2);
     q2_.Enqueue(3);
  }

  // void TearDown() override {}

  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.

在这个例子中,就不需要TearDown()了,因为我们不需要在每个测试之后清理,只需要清理析构函数已经完成的工作。

Now we’ll write tests using TEST_F() and this fixture.

现在我们将使用TEST_F()和这个fixture编写测试。

TEST_F(QueueTest, IsEmptyInitially) {
  EXPECT_EQ(q0_.size(), 0);
}

TEST_F(QueueTest, DequeueWorks) {
  int* n = q0_.Dequeue();
  EXPECT_EQ(n, nullptr);

  n = q1_.Dequeue();
  ASSERT_NE(n, nullptr);
  EXPECT_EQ(*n, 1);
  EXPECT_EQ(q1_.size(), 0);
  delete n;

  n = q2_.Dequeue();
  ASSERT_NE(n, nullptr);
  EXPECT_EQ(*n, 2);
  EXPECT_EQ(q2_.size(), 1);
  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_NE(n, nullptr), as we need to dereference the pointer n later, which would lead to a segfault when n is NULL.

上面的代码同时使用了ASSERT_*EXPECT_*断言。经验法则是,当你希望测试在断言失败后继续发现更多错误时,使用EXPECT_*,而当失败后继续没有意义时,使用ASSERT_*。例如,出队列测试中的第二个断言是ASSERT_NE(n, nullptr),因为我们稍后需要解引指针n,当n为NULL时,这会导致段错误。

When these tests run, the following happens:

运行这些测试时,会发生以下情况:

  1. googletest constructs a QueueTest object (let’s call it t1).

googletest构造了一个QueueTest对象(我们称它为t1)。

  1. t1.SetUp() initializes t1.

t1. setup()初始化t1。

  1. The first test (IsEmptyInitially) runs on t1.

第一个测试(IsEmptyInitially)运行在t1上。

  1. t1.TearDown() cleans up after the test finishes.

t1.TearDown()在测试结束后进行清理工作。

  1. t1 is destructed.

T1被销毁。

  1. The above steps are repeated on another QueueTest object, this time running the DequeueWorks test.

在另一个QueueTest对象上重复上述步骤,这次运行DequeueWorks测试。

Availability: Linux, Windows, Mac.

Invoking the Tests


TEST() and TEST_F() implicitly register their tests with googletest. 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()隐式地将它们的测试注册到googletest。因此,与许多其他c++测试框架不同,你不必重新列出所有定义的测试来运行它们。

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 suites, or even different source files.

定义测试后,你可以使用RUN_ALL_TESTS()运行它们,如果所有测试都成功,则返回0,否则返回1。请注意,RUN_ALL_TESTS()运行链接单元中的所有测试——它们可以来自不同的测试套件,甚至不同的源文件。

When invoked, the RUN_ALL_TESTS() macro:

当调用RUN_ALL_TESTS()宏时:

  • Saves the state of all googletest flags.

保存所有googletest标志的状态。

  • Creates a test fixture object for the first test.

为第一个测试创建一个测试夹具对象。

  • Initializes it via SetUp().

通过SetUp()初始化它。

  • Runs the test on the fixture object.

在fixture对象上运行测试。

  • Cleans up the fixture via TearDown().

通过TearDown()清理fixture。

  • Deletes the fixture.

删除夹具。

  • Restores the state of all googletest flags.

恢复所有googletest标志的状态。

  • Repeats the above steps for the next test, until all tests have run.

在下一个测试中重复上述步骤,直到所有测试都运行完毕。

If a fatal failure happens the subsequent steps will be skipped.

如果发生致命故障,则跳过后续步骤。

[IMPORTANT]
You must not ignore the return value of RUN_ALL_TESTS(), or you will get 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()的返回值,否则会得到编译器错误。这种设计的基本原理是,自动化测试服务根据其退出代码确定测试是否通过,而不是根据其stdout/stderr输出;因此main()函数必须返回RUN_ALL_TESTS()的值。

Also, you should call RUN_ALL_TESTS() only once. Calling it more than once conflicts with some advanced googletest features (e.g., thread-safe death tests) and thus is not supported.

此外,您应该只调用RUN_ALL_TESTS()一次。多次调用它会与一些高级googletest功能(例如,线程安全死亡测试)冲突,因此不支持。

Availability: Linux, Windows, Mac.

Writing the main() Function

Most users should not need to write their own main function and instead link with gtest_main (as opposed to with gtest), which defines a suitable entry point. See the end of this section for details. The remainder of this section should only apply when you need to do something custom before the tests run that cannot be expressed within the framework of fixtures and test suites.

大多数用户不需要编写自己的main函数,而是链接到gtest_main(而不是gtest),它定义了一个合适的入口点。详情见本节末尾。本节剩下的内容只适用于在运行测试之前需要执行一些自定义操作,而这些操作无法在fixture和测试套件框架中表达的情况。

If you write your own main function, it should return the value of RUN_ALL_TESTS().

如果编写自己的主函数,它应该返回RUN_ALL_TESTS()的值。

You can start from this boilerplate:
你可以从这个样板文件开始:

#include "this/package/foo.h"

#include "gtest/gtest.h"

namespace my {
namespace project {
namespace {

// The fixture for testing class Foo.
class FooTest : public ::testing::Test {
 protected:
  // You can remove any or all of the following functions if their bodies would
  // be empty.

  FooTest() {
     // You can do set-up work for each test here.
  }

  ~FooTest() override {
     // 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:

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

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

  // Class members declared here can be used by all tests in the test suite
  // for Foo.
};

// Tests that the Foo::Bar() method does Abc.
TEST_F(FooTest, MethodBarDoesAbc) {
  const std::string input_filepath = "this/package/testdata/myinputfile.dat";
  const std::string output_filepath = "this/package/testdata/myoutputfile.dat";
  Foo f;
  EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0);
}

// Tests that Foo does Xyz.
TEST_F(FooTest, DoesXyz) {
  // Exercises the Xyz feature of Foo.
}

}  // namespace
}  // namespace project
}  // namespace my

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

The ::testing::InitGoogleTest() function parses the command line for googletest 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 the AdvancedGuide. You must call this function before calling RUN_ALL_TESTS(), or the flags won’t be properly initialized.

函数::testing::InitGoogleTest()解析命令行中的googletest标志,并删除所有可识别的标志。这允许用户通过各种标志控制测试程序的行为,我们将在高级指南中介绍。必须在调用RUN_ALL_TESTS()之前调用此函数,否则标志将无法正确初始化。

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 the gtest_main library and you are good to go.

但也许你认为编写所有这些主函数的工作量太大了?我们完全同意你的观点,这就是为什么谷歌测试提供了main()的基本实现。如果它符合您的需求,那么只需将您的测试链接到gtest_main库就可以了。

[NOTE]: ParseGUnitFlags() is deprecated in favor of InitGoogleTest().

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.

谷歌测试被设计为线程安全的。在pthreads库可用的系统上,该实现是线程安全的。目前,在其他系统(例如Windows)上从两个线程并发地使用谷歌测试断言是不安全的。在大多数测试中,这不是问题,因为断言通常在主线程中完成。如果您想提供帮助,您可以自愿为您的平台实现gtest-port.h中必要的同步原语。

GoogleTest · GitHub Repository · License · Privacy Policy

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值