文章目录
- GoogleTest Primer(GoogleTest入门指南)
- Introduction: Why GoogleTest?(简介:为什么选择GoogleTest?)
- Beware of the Nomenclature(小心术语)
- Basic Concepts(基本概念)
- Assertions(断言)
- Simple Tests(简单测试)
- Test Fixtures: Using the Same Data Configuration for Multiple Tests(测试夹具:对多个测试使用相同的数据配置)
- Invoking the Tests(调用测试)
- Writing the main() Function(编写main()函数)
- Known Limitations(已知限制)
GoogleTest Primer(GoogleTest入门指南)
Introduction: Why GoogleTest?(简介:为什么选择GoogleTest?)
GoogleTest helps you write better C++ tests.
GoogleTest可以帮助您编写更好的C++测试用例。
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是如何实现的呢?我们认为:
- 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允许您隔离运行它以进行快速调试。 - 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将相关测试分组到可以共享数据和子例程的测试套件中。这种常见模式易于识别,并使测试易于维护。当人们切换项目并开始使用新的代码库时,这种一致性尤其有用。 - 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测试可以使用各种配置。 - 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不会在第一次测试失败时停止。相反,它只停止当前测试并继续下一个测试。您还可以设置报告非致命故障的测试,然后继续当前测试。因此,您可以在一个运行-编辑-编译周期中检测并修复多个错误。 - 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自动跟踪所有定义的测试,不需要用户为了运行它们而枚举它们。 - 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.
注意:术语“Test”、“Test Case”和“Test Suite”的不同定义可能会引起一些混淆,所以要小心误解。
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中使用的相关术语Test对应于ISTQB和其他公司的术语Test Case。
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.
Test一词通常意义足够广泛,包括ISTQB对Test Case的定义,所以它在这里不是什么大问题。但GoogleTest中使用的Test Case一词是矛盾的,因此令人困惑。
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:
因此,请注意这些术语的不同定义:
Meaning | GoogleTest Term | ISTQB Term |
---|---|---|
Exercise a particular program path with specific input values and verify the results(使用特定的输入值练习特定的程序路径并验证结果) | 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_EQ和EXPECT_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字符串和string对象。如果将宽字符串(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:
要创建测试:
- Use the
TEST()
macro to define and name a test function. These are ordinary C++ functions that don’t return a value.
使用TEST()
宏来定义和命名测试函数。这些是不返回值的普通C++函数。 - In this function, along with any valid C++ statements you want to include, use the various GoogleTest assertions to check values.
在这个函数中,连同您想要包含的任何有效C++语句一起,使用各种GoogleTest断言来检查值。 - 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:
例如,让我们取一个简单的整数函数:
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.
可用性: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.
如果您发现自己编写了两个或多个对类似数据进行操作的测试,那么可以使用测试夹具。这允许您为几个不同的测试重用相同的对象配置。
To create a fixture:
要创建夹具:
- Derive a class from
testing::Test
. Start its body withprotected:
, as we’ll want to access fixture members from sub-classes.
从testing::Test
派生一个类,它的主体以protected:开头,因为我们希望从子类访问fixture成员。 - Inside the class, declare any objects you plan to use.
在类内部,声明您计划使用的任何对象。 - If necessary, write a default constructor or
SetUp()
function to prepare the objects for each test. A common mistake is to spellSetUp()
asSetup()
with a smallu
- Useoverride
in C++11 to make sure you spelled it correctly.
如果需要,可以编写一个默认的构造函数或SetUp()函数来为每个测试准备对象。一个常见的错误是用一个小u将SetUp()拼写为SetUp() - 在C++11中使用override来确保拼写正确。 - If necessary, write a destructor or
TearDown()
function to release any resources you allocated inSetUp()
. To learn when you should use the constructor/destructor and when you should useSetUp()/TearDown()
, read the FAQ.
如果需要,可以编写一个析构函数或TearDown()函数来释放在SetUp()中分配的任何资源。要了解何时应该使用构造函数/析构函数以及何时应该使用SetUp()/TearDown(),请阅读常见问题解答。 - 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:
使用夹具时,请使用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代表“夹具”)。没有为此宏指定测试套件名称。
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()中使用测试夹具类之前,必须先定义它,否则会得到编译器错误“虚拟外部类声明”。
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不会在多个测试中重复使用同一个测试夹具。一个测试对夹具所做的任何更改都不会影响其他测试。
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_*。例如,Dequeue测试中的第二个断言是ASSERT_NE(n,nullptr),因为我们稍后需要取消引用指针n,当n为NULL时,这将导致segfault。
When these tests run, the following happens:
当这些测试运行时,会发生以下情况:
- GoogleTest constructs a
QueueTest
object (let’s call itt1
).
GoogleTest构建了一个QueueTest对象(我们称之为t1)。 t1.SetUp()
initializest1
.
t1.SetUp()初始化t1- The first test (
IsEmptyInitially
) runs ont1
.
第一个测试(IsEmptyInitially)在t1上运行。 t1.TearDown()
cleans up after the test finishes.
t1.TearDown()在测试结束后进行清理。t1
is destructed.
t1被销毁- The above steps are repeated on another
QueueTest
object, this time running theDequeueWorks
test.
在另一个QueueTest对象上重复上述步骤,这次运行DequeueWorks测试。
Availability: Linux, Windows, Mac.
可用性: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.
运行测试夹具中的测试 - Cleans up the fixture via
TearDown()
.
通过TearDown()清理测试夹具。 - 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 yourmain()
function must return the value ofRUN_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.
可用性:Linux、Windows、Mac。
Writing the main() Function(编写main()函数)
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)进行链接,后者定义了一个合适的入口点。有关详细信息,请参见本节末尾。本节的其余部分仅适用于在测试运行之前需要进行自定义操作的情况,而这些操作无法在夹具的框架和测试套件的框架中表达。
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标志,并删除所有可识别的标志。这允许用户通过各种标志来控制测试程序的行为,我们将在AdvancedGuide中介绍这些标志。必须在调用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 ofInitGoogleTest()
.
注意:不赞成使用ParseGUnitFlags(),而赞成使用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 ingtest-port.h
for your platform.
谷歌测试是为线程安全而设计的。在pthreads库可用的系统上,实现是线程安全的。目前,在其他系统(如Windows)上同时使用来自两个线程的Google测试断言是不安全的。在大多数测试中,这不是一个问题,因为断言通常在主线程中完成。如果您想提供帮助,可以自愿在gtestport.h中为您的平台实现必要的同步原语。
GoogleTest · GitHub Repository · License · Privacy Policy