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. 只測試這個類的 測試用例

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章