cmake-gtest单元测试


title: cmake-gtest单元测试
categories: CMake
tags: [cmake, gtest, 单元测试]
date: 2020-02-17 10:38:43
comments: false

cmake-gtest单元测试


前篇

  • 官方
    • GitHub: https://github.com/google/googletest
  • clion 官方 gtest-config - https://www.jetbrains.com/help/clion/creating-google-test-run-debug-configuration-for-test.html#gtest-config
  • Google Test(gtest)使用 - http://notes.maxwi.com/2017/11/29/gtest/

集成 gtest

  • CLion下的gtest测试 - https://blog.csdn.net/weixin_38988633/article/details/92801084

这里使用的 clion 编辑器


TEST

  1. 在项目中添加一个 子模块 引入 gtest.

  2. CMakeLists.txt 中加入 gtest. 附: 测试代码

    # 测试 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
    
  3. done.

    • 测试所有用例. 直接 build and run.

      // ----------- 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
      
    • 测试单个用例, 直接在 用例 上 右键 -> Run TestCase.xxx


TEST_F

  1. 添加一个类 GTestDemo 继承 ::testing::Test, 这个 GTestDemo 就是一个 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;
    }
    
  2. done. 只测试这个类的 测试用例

    扫描二维码关注公众号,回复: 12761105 查看本文章

    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 添加 单元测试 配置

  • 官方 gtest-config - https://www.jetbrains.com/help/clion/creating-google-test-run-debug-configuration-for-test.html#gtest-config

测试所有用例

  1. 添加一个测试配置. 使用 suite/test 模式, suite 留空代表测试所有 test suite

    • program arguments : 这里可以加入 可选参数, 指定测试某些用例
  2. 跑一下.

    哪个 过了/没过 一目了然.


带信息的 assert

  • https://stackoverflow.com/questions/16491675/how-to-send-custom-message-in-google-c-testing-framework

往后面加上 << "xxx" 即可

ASSERT_TRUE(false) << "--- err: wolegequ"; // 将中断执行
EXPECT_TRUE(false) << "--- err: wolegequ"; // 不中断执行, 会报用例测试失败

指定测试用例

参数: --gtest_filter=*.*, 匹配符合条件的用例.

  1. 测试用例

    TEST(TestCase, test3) {
          
          
        std::cout << "---- test3 hello world" << std::endl;
        EXPECT_EQ(3, add(1, 2));
    }
    
  2. 指定测试

    $ .\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.
    

可选参数

可以在可执行程序后面加入一些参数. 例如:

$ .\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.

所有可选参数:

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


测试代码

// ----------- 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();
}

猜你喜欢

转载自blog.csdn.net/yangxuan0261/article/details/104358123