当前位置:网站首页>GTEST from getting started to getting started
GTEST from getting started to getting started
2022-06-24 11:35:00 【CarnivoreRabbit】
GTest From entry to entry
1 GTest brief introduction
GTest yes Google Open source library , Is a powerful cross platform C++ Test library . For developers who are not test engineers , Study GTest It is conducive to unit testing of code .
GTest Is more than unit testing , in fact ,GTest It can be applied to various tests .
GTest It is said in the document of . But Xiaobai is just a beginner programmer , So it is very satisfying to do unit tests well .
2 GTest 1.8.1 VS2013+CMake compile
GTest As an open source project , stay github It has complete source code and is still under maintenance
GTest Portal
By the time Xiaobai wrote this blog ,GTest The latest version of is v1.11.0, But unfortunately , This latest version does not support VS2013, It has to be VS2015 The above can be used . Given the limited tools used by Xiaobai's team , Xiaobai can only select the last support VS2013 Of GTest edition , namely v1.8.1.
from github Upper handle v1.8.1 Download the source code of version , And then use CMake Compile .
This compilation process is very simple , Than the GLOG A lot of holes are missing .
The default configuration is fine , There is no need to change any tick .
After opening the project , direct “ Generate ”->“ Batch generation ”->ALL_BUILD and INSTALL Of Release x64 Generate .
Then fall into the first pit :
The two here bug It's not a big deal , Just change it gmock and gmock_main Properties under two items :
stay C/C++ -> routine -> “ Treat warnings as errors ” Selected as “ no ”.
Try it again , It is possible to meet the following bug:
This problem needs to be solved in INSTALL Under the properties of the project , modify “ Configuration properties ”-> “ Generate an event ”-> “ Post generated events ”, hold “ Command line ” The code in one line is deleted . This line of command requires administrator privileges , Xiaobai, there is no . Simple and crude , Why don't you carry out relevant operations , After all, we call it through a third-party library , There is no need to register with the system .
If all goes well , There should be 7 Projects compiled successfully :
At this point, the compilation should be successful , We will build another project testGtest Directory as follows :
├─3rdparty
│ └─gtest
│ ├─include
│ │ └─gtest
│ │ └─internal
│ │ └─custom
│ └─lib
├─build
│ └─x64
│ └─Release
├─source
└─windows
└─testGtest
└─x64
└─Release
└─testGtest.tlog
Just pay special attention here 3rdparty The structure of the directory :
gtest Of include Next, we must follow gtest Source path relationship settings for , For details, please refer to the googletest-release-1.8.1\googletest\include\gtest
lib You only need the newly compiled gtest.lib and gtest_mock.lib, These two files are from the just compiled build The next path build\googlemock\gtest\Release Just look for it .( There are a few pits here , The location of the compiled library is googlemock Under the table of contents , There is no direct gtest or googletest Catalog )
Come here , Our preparations are done .( I have to sigh , It's better than GLOG There are many fewer pitfalls encountered during compilation ).
3. GTest Basics
GTest Well documented , The address in GoogleTest Primer.
Since our aim is to be practical , So I just need to understand some basic contents :
3.1 Discrimination of several concepts
test 、test case、 test suitetest case Is a common concept in the testing field , Test case . But in GTest in ,test case It refers to a set of tests , Instead of a single use case in the usual concept .GTest The single test case mentioned in is a noun test. In order to unify ,GTest Use consciously in recent releases test suite To replace the original test case, Prevent confusion .
GTest Our tests are basically based on groups , for “ Group ” Provide a name . Next TEST() Macro will be introduced in detail .
3.2 TEST() ASSERT and EXPECT macro
GTest The assertion used is actually a macro similar to a function call . You can test by asserting the behavior of a class or function . When the assertion fails ,GTest The source file and line number location of the assertion will be printed , And a failure message .GTest It also allows you to provide a customized failure message , This information can be added to the information attached to the assertion .
Assertions occur in pairs ,ASSERT_* and EXPECT_* The macros of both assertion classes can implement tests , The difference is ,ASSERT_* Once the assertion of type is falsified , The test program will be terminated directly , And if EXPECT_* The assertion of type is falsified , Will not immediately abort the program , Instead, it will continue to execute the program .
Therefore, it is more recommended that EXPECT_* Assertion of type .
Here is an example to judge x and y Whether the length is equal , And find examples of different elements :
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 ostream Can be streamed to the assertion macro , In especial C Strings and string objects . If the wide string (wchar_t*、Windows On UNICODE Mode of TCHAR* or std::wstring) Stream to assertion , Will be converted to UTF-8.
Create the test :
- Use
TEST()Macro definition and naming test functions . These are ordinary C++ Functions with no return value . - In this function , And any valid C++ sentence , Please use various googletest Assert to check the value .
- The result of the test is determined by the assertion ; If any assertion in the test fails ( Fatal or non fatal ), Or the test crashes , Then the whole test fails . otherwise , It will succeed .
TEST(TestSuiteName, TestName) {
... test body ...
}
TEST() Parameters range from general to specific . The first parameter is the test suite test suite The name of , The second parameter is the name of the test in the test suite test name. Both names must be valid C++ identifier , And should not contain any underscores (_). The full name of a test consists of the test suite it contains and a single name . Tests from different test suites can have the same single name .
for example , An ordinary integer return value function
int Factorial(int n); // return n The factorial
A test suite test suite It could be as follows :
// 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 Group test results by test suite , Therefore, logically related tests should be in the same test suite ; let me put it another way , their TEST() The first parameter of should be the same . In the example above , We have two tests ,HandlesZeroInput and HandlesPositiveInput, They belong to the same test suite FactorialTest.
3.3 RUN_ALL_TESTS()
After defining the test , have access to RUN_ALL_TESTS() Run them , If all tests are successful , Then return to 0, Otherwise return to 1. Please note that ,RUN_ALL_TESTS() Run all tests in the linked unit - They can come from different test suites , It can even come from different source files .
It can be loosely summarized as :RUN_ALL_TESTS() It is the unified entrance and exit of the whole test program .
Invocation time ,RUN_ALL_TESTS() macro :
- Save the status of all Google test flags .
- Create a test fixture object for the first test ( About the fixture , see also TEST_F macro , This article does not cover ).
- adopt SetUp() Initialize it .
- Run tests on fixture objects .
- adopt TearDown() Cleaning fixture .
- Delete fixture .
- Restore the status of all Google test marks .
- Repeat the above steps for the next test , Until all tests have been run .
- If a fatal failure occurs , Next steps will be skipped .
Important note : Can't ignore
RUN_ALL_TESTS()The return value of , Otherwise you will receive a compiler error . The basic principle of this design is , Automatic test service according to its exit code ( instead of stdout/stderr Output ) Determine if the test has passed ; therefore ,main()The function must returnRUN_ALL_TESTS()Value .
in addition ,RUN_ALL_TESTS()Only one call is allowed . Call it more than once with some advanced googletest function ( for example , Thread safe death test ) Conflict , So not supported .
3.4 ::testing::InitGoogleTest(&argc, argv) and main()
Most users do not need to write their own main function , But with gtest_main( instead of gtest) link , This defines a suitable entry point . The rest of this section should only apply if you need to perform custom actions before the test run , These customizations cannot be represented within the framework of fixtures and test suites .
The sample code is so long :
#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();
}
::testing::InitGoogleTest() Function analysis googletest Command line for flags , And delete all identification marks . This allows the user to control the behavior of the test program through various flags , We will introduce these signs in the advanced Guide . Calling RUN_ALL_TESTS() Before , This function must be called , Otherwise, the flag will not initialize correctly .
stay Windows On ,InitGoogleTest() It also applies to wide strings , So it can also be in UNICODE Used in programs compiled in mode .
3.5 Example of Xiaobai
#include <gtest/gtest.h>
#include <iostream>
using namespace std;
int add(int a, int b)
{
return a + b;
}
TEST(AddTest, Positive)
{
EXPECT_EQ(add(2, 3), 5);
EXPECT_EQ(add(2, 4), 6);
}
TEST(AddTest, Negative)
{
EXPECT_EQ(add(-2, -3), -5);
EXPECT_EQ(add(-2, -1), -3);
}
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Use cmd The tool runs and views the results :
You can see that all the tests here have passed , The green light is everywhere .
To see the wrong result , We deliberately modified the code .
TEST(AddTest, Negative)
{
EXPECT_EQ(add(-2, -3), -5);
EXPECT_EQ(add(-2, -1), -4); // Forcibly change “ right key ”
}
Then we got the test result with red light :
We can see that all the tests have been completed , And gives or passed or failed Result .
3.6 Advanced TEST_F() macro
This part of the content has been roughly browsed , Its main usage and TEST() Macros are nearly identical , But its biggest function is that the test data can be reused for multiple tests .
Because this article is just “ From entry to entry ”, The content here will be reserved for further use and research in the future .
【 And the limit of the level , It's hard to avoid mistakes 】
【 It's not easy to create , Spray gently and don't scold 】

边栏推荐
猜你喜欢

AXI低功耗接口

"One good programmer is worth five ordinary programmers!"

软件测试 对前一日函数的基本路径测试

How stupid of me to hire a bunch of programmers who can only "Google"!

工具及方法 - 在Source Insight中使用代码格式化工具
Database migration tool flyway vs liquibase (II)
![[graduation season · attacking technology Er] three turns around the tree, what branch can we rely on?](/img/0a/0ebfa1e5c1bea6033b538528242252.png)
[graduation season · attacking technology Er] three turns around the tree, what branch can we rely on?

Today in history: Turing's birth day; The birth of the founder of the Internet; Reddit goes online

脚本之美│VBS 入门交互实战

计组_cpu的结构和工作流程
随机推荐
A fault record of misoperation dhclient script
Tools and methods - use code formatting tools in source insight
11+的基于甲基化组和转录组综合分析识别葡萄膜黑色素瘤中新的预后 DNA 甲基化特征~
Influence of DEX optimization on arouter lookup path
Using the collaboration database query of Poole in laravel5.6
如何开发短信通知和语音功能医院信息系统(HIS系统)
我在深圳,到哪里开户比较好?现在网上开户安全么?
[latest - lightweight cloud servers - hot sales] new lightweight application server optimization scheme, 1-core 2g5m time limit as low as 99 yuan / year
[the lottery in May has ended, and the list of winners has been announced] special session of techo youth university open course database
为什么虚拟机ping的通主机,主机ping不通虚拟机
ahk实现闹钟
math_ Summation and derivation of proportional series & derivation of sum and difference of equal powers / difference between two nth power numbers/
PHP短信通知+语音播报自动双呼
Tencent geek challenge small - endless!
Libuv的安装及运行使用
Google ranging for PHP wechat development
Istio best practice: graceful termination
Basic path test of software test on the function of the previous day
Moving Tencent to the cloud cured their technical anxiety
TP-LINK 1208路由器教程(2)