title: cmake-gtest unit test
categories: CMake
tags: [cmake, gtest, unit test]
date: 2020-02-17 10:38:43
comments: false
cmake-gtest unit test
Prequel
- official
- GitHub: https://github.com/google/googletest
- clion official gtest-config-https://www.jetbrains.com/help/clion/creating-google-test-run-debug-configuration-for-test.html#gtest-config
- Google Test (gtest) use-http://notes.maxwi.com/2017/11/29/gtest/
Integrated gtest
- Gtest test under CLion-https://blog.csdn.net/weixin_38988633/article/details/92801084
Clion editor used here
TEST
-
Adding a project in sub-module introduced gtest .
-
Add gtest to CMakeLists.txt . Attachment: Test code
# 测试 gtest 的代码 file(GLOB_RECURSE SRC_GTest GTest/add/*.h GTest/add/*.cpp ) #set(mainCpp main.cpp) set(mainCpp GTest/main.cpp) # gtest 入口文件 set(SOURCE_FILES ${mainCpp} ${SRC_OtherTest} ${SRC_ExternTest} ${AlgorithmTest} ${SRC_GTest}) ############# googletest module begin ############# set(gtName gtest) # gtest 库名 add_subdirectory(googletest) # gtest 目录 include_directories(googletest/googletest/include) link_directories( ${CMAKE_CURRENT_SOURCE_DIR}/googletest # gtest 头文件目录 ) ############# googletest module end ############# add_executable(${PROJECT_NAME} ${SOURCE_FILES}) target_link_libraries(${PROJECT_NAME} ${gtName}) # 链接 gtest
-
done.
-
Test all use cases. Build and run directly.
// ----------- build ----------- "D:\CLion 2019.3.3\bin\cmake\win\bin\cmake.exe" --build E:\ws_cpp\CppLab\cmake-build-debug --target CppLab -- -j 6 [ 3%] Built target gtest [100%] Built target CppLab Build finished // ----------- run ----------- E:\ws_cpp\CppLab\cmake-build-debug\CppLab.exe [==========] Running 3 tests from 1 test suite. [----------] Global test environment set-up. [----------] 3 tests from TestCase [ RUN ] TestCase.test1 ---- test1 hello world [ OK ] TestCase.test1 (0 ms) [ RUN ] TestCase.test2 ---- test2 hello world [ OK ] TestCase.test2 (1 ms) [ RUN ] TestCase.test3 ---- test3 hello world [ OK ] TestCase.test3 (2 ms) [----------] 3 tests from TestCase (15 ms total) [----------] Global test environment tear-down [==========] 3 tests from 1 test suite ran. (31 ms total) [ PASSED ] 3 tests. Process finished with exit code 0
-
Test a single use case, directly in the use case right -> Run TestCase.xxx
-
TEST_F
-
Add a class
GTestDemo
inheritance::testing::Test
, thisGTestDemo
is a the Test Suite .// ----------- demotest.cpp ----------- #include <iostream> #include "gtest/gtest.h" class GTestDemo : public ::testing::Test { private: int mNum1 = 123; // 测试框架访问不到 public: int mNum2 = 456; GTestDemo() : Test() { std::cout << "------ constructor" << std::endl; } ~GTestDemo() { std::cout << "--- deconstructor" << std::endl; } virtual void SetUp() { Test::SetUp(); std::cout << "--- SetUp" << std::endl; } virtual void TearDown() { Test::TearDown(); std::cout << "--- TearDown" << std::endl; } }; TEST_F(GTestDemo, tc_example_01) { std::cout << "tc_example_01: " << mNum2 << std::endl; } TEST_F(GTestDemo, tc_example_02) { std::cout << "tc_example_02" << std::endl; }
-
done. Only test the test cases of this class
E:\ws_cpp\CppLab\cmake-build-debug\CppLab.exe --gtest_color=no Running 2 tests from 1 test suite.------ constructor --- SetUp tc_example_01: 456 --- TearDown --- deconstructor ------ constructor --- SetUp tc_example_02 --- TearDown --- deconstructor 2 tests from 1 test suite ran. (0 ms total)Process finished with exit code 0
clion add unit test configuration
- Official gtest-config-https://www.jetbrains.com/help/clion/creating-google-test-run-debug-configuration-for-test.html#gtest-config
Test all use cases
-
Add a test configuration. Use suite/test mode, leave the suite blank to test all test suites
- program arguments: there may be added optional parameter specifying test some use cases
-
Run.
It's clear at a glance which passed/n't passed.
Assert with information
- https://stackoverflow.com/questions/16491675/how-to-send-custom-message-in-google-c-testing-framework
To add back << "xxx"
to
ASSERT_TRUE(false) << "--- err: wolegequ"; // 将中断执行
EXPECT_TRUE(false) << "--- err: wolegequ"; // 不中断执行, 会报用例测试失败
Specify test cases
Parameters:, --gtest_filter=*.*
match the use cases that meet the conditions.
-
Test case
TEST(TestCase, test3) { std::cout << "---- test3 hello world" << std::endl; EXPECT_EQ(3, add(1, 2)); }
-
Specified test
$ .\CppLab.exe --gtest_filter=TestCase.test3 # 只测试 TestCase.test3 这个用例 Active code page: 65001 Note: Google Test filter = TestCase.test3 [==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from TestCase [ RUN ] TestCase.test3 ---- test3 hello world [ OK ] TestCase.test3 (0 ms) [----------] 1 test from TestCase (10 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test suite ran. (44 ms total) [ PASSED ] 1 test.
Optional parameters
You can add some parameters after the executable program. For example:
$ .\CppLab.exe --gtest_filter=CBaseTest.test_* # 只测试匹配 CBaseTest.test_* 的用例, CBaseTest 一个test suit
Note: Google Test filter = CBaseTest.test_*
[==========] Running 11 tests from 1 test suite. # 匹配到 11 个需要测试的用例
[----------] Global test environment set-up.
[----------] 11 tests from CBaseTest
[ RUN ] CBaseTest.test_string # 测试用例
--- destPath: aaa/vvv/
[ OK ] CBaseTest.test_string (14 ms) # 结果
...
[----------] 11 tests from CBaseTest (186 ms total)
[----------] Global test environment tear-down
[==========] 11 tests from 1 test suite ran. (220 ms total)
[ PASSED ] 11 tests.
All optional parameters:
This program contains tests written using Google Test. You can use the
following command line flags to control its behavior:
Test Selection:
--gtest_list_tests
List the names of all tests instead of running them. The name of
TEST(Foo, Bar) is "Foo.Bar".
--gtest_filter=POSTIVE_PATTERNS[-NEGATIVE_PATTERNS]
Run only the tests whose name matches one of the positive patterns but
none of the negative patterns. '?' matches any single character; '*'
matches any substring; ':' separates two patterns.
--gtest_also_run_disabled_tests
Run all disabled tests too.
Test Execution:
--gtest_repeat=[COUNT]
Run the tests repeatedly; use a negative count to repeat forever.
--gtest_shuffle
Randomize tests' orders on every iteration.
--gtest_random_seed=[NUMBER]
Random number seed to use for shuffling test orders (between 1 and
99999, or 0 to use a seed based on the current time).
Test Output:
--gtest_color=(yes|no|auto)
Enable/disable colored output. The default is auto.
--gtest_print_time=0
Don't print the elapsed time of each test.
--gtest_output=(json|xml)[:DIRECTORY_PATH\|:FILE_PATH]
Generate a JSON or XML report in the given directory or with the given
file name. FILE_PATH defaults to test_detail.xml.
Assertion Behavior:
--gtest_break_on_failure
Turn assertion failures into debugger break-points.
--gtest_throw_on_failure
Turn assertion failures into C++ exceptions for use by an external
test framework.
--gtest_catch_exceptions=0
Do not report exceptions as test failures. Instead, allow them
to crash the program or throw a pop-up (on Windows).
Except for --gtest_list_tests, you can alternatively set the corresponding
environment variable of a flag (all letters in upper-case). For example, to
disable colored text output, you can either specify --gtest_color=no or set
the GTEST_COLOR environment variable to no.
For more information, please read the Google Test documentation at
https://github.com/google/googletest/. If you find a bug in Google Test
(not one in your own code or tests), please report it to
<googletestframework@googlegroups.com>.
Process finished with exit code 0
Test code
// ----------- add.h -----------
#ifndef TESTADD2_ADD_H
#define TESTADD2_ADD_H
int add(int n1,int n2);
#endif //TESTADD2_ADD_H
// ----------- add.cpp -----------
#include "add.h"
int add(int n1, int n2) {
return n1 + n2;
}
// ----------- main.cpp -----------
#include <iostream>
#include "add/add.h"
#include "gtest/gtest.h" // 引入 gtest
TEST(TestCase, test1) {
std::cout << "---- test1 hello world" << std::endl;
ASSERT_EQ(12, add(4, 8));
}
TEST(TestCase, test2) {
std::cout << "---- test2 hello world" << std::endl;
EXPECT_EQ(5, add(2, 3));
}
TEST(TestCase, test3) {
std::cout << "---- test3 hello world" << std::endl;
EXPECT_EQ(3, add(1, 2));
}
GTEST_API_ int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}