clion cmake工程使用 gtest

  1. github上下载Google Test。并放到工程文件夹下。
工程目录结构如下:
☺  tree -L 1                                                                                               master ✗
.
├── CMakeLists.txt
├── CMakeLists.txt.user
├── cmake-build-debug
├── googletest
├── main.cpp
└── src

googletest是之前从github上下载下来Google Test的仓库,并重命名后的。
src中的test目录是测试目录。
src下放【测试目录】和 自己的工程源码们:
☺  tree src                                                                                                master ✗
src
├── include
│   └── Config.h
├── test
│   └── utility
│       └── CellGameCoreTest.cpp
├── ui
│   ├── widget
│   │   └── game
│   │       ├── GameWidget.cpp
│   │       └── GameWidget.h
│   └── window
│       └── mainwindow
│           ├── MainWindow.cpp
│           ├── MainWindow.h
│           └── mainwindow.ui
└── utility
    ├── CellGameCore.cpp
    ├── CellGameCore.h
    └── Rand_int.h

2. 项目的CmakeList.txt中需要引入GoogleTest。如下,引入了gtest和gmock

add_subdirectory(googletest)
include_directories(googletest/googletest/include)
include_directories(googletest/googlemock/include)
target_link_libraries(CellGame gtest gtest_main)
target_link_libraries(CellGame gmock gmock_main)

3. 接着开始写测试文件。可以看到test中采取了与工程类似的目录架构,这种架构风格还不错。

☺  tree src/test -L 3                                                                                      master ✗
src/test
└── utility
    └── CellGameCoreTest.cpp

TEST宏是gtest中的,第一个参数是Test Suit Name, 第二个参数是 Test Name。这两个Name之前有层级关系。在TEST中可以使用ASSERT_EQ等宏。

//
// Created by perci on 2020/5/21.
//

#include <src/utility/CellGameCore.h>
#include <vector>
#include "gtest/gtest.h"
TEST(CellGameCoreTest, SampleTest) {
    CellGameCore core;
    std::vector<std::vector<int>> vs;
    vs.push_back(std::vector<int> {1,1,1});
    vs.push_back(std::vector<int> {0,0,0});
    vs.push_back(std::vector<int> {0,0,0});
    std::vector<std::vector<int>> vs2 = core.process(vs);

    ASSERT_EQ(vs2[0][0], 0);
    ASSERT_EQ(vs2[0][1], 1);
    ASSERT_EQ(vs2[0][2], 0);
    ASSERT_EQ(vs2[1][1], 1);

    return;
}

TEST(CellGameCoreTest, SampleTest2) {
    CellGameCore core;
    std::vector<std::vector<int>> vs;
    vs.push_back(std::vector<int> {1,0,0});
    vs.push_back(std::vector<int> {0,1,0});
    vs.push_back(std::vector<int> {0,0,1});
    std::vector<std::vector<int>> vs2 = core.process(vs);

    ASSERT_EQ(vs2[0][0], 0);
    ASSERT_EQ(vs2[0][1], 0);
    ASSERT_EQ(vs2[0][2], 0);
    ASSERT_EQ(vs2[1][1], 1);
}

4. 需要在CmakeList.txt中将测试文件添加到工程中。这里add_executable中新增了一个mytest的。

add_executable(mytest src/test/utility/CellGameCoreTest.cpp src/utility/CellGameCore.cpp)
target_link_libraries(mytest gtest gtest_main)

同时因为CellGameCoreTest.cpp中使用CellGameCore这个类,就引入了CellGameCore.cpp。(CellGameCore.cpp中引入了CellGameCore.h, 这样就相当于把这两个文件都引入了。光引入.h是不行的。)

5. 接着reload CmakeList.txt后,就会发现项目的Configuration

中有了mytest,接着就可以跑起测试了