- 从一个干净的目录开始:
/home/user/Desktop/projects/cpp/ # your project lives here
- 添加您的 cmake 文件 (CMakeLists.txt)、源文件和测试文件。该目录现在如下所示:
└─cpp/
├─ CMakeLists.txt
├─ myfunctions.h
└─ mytests.cpp
- 克隆并将
googletest 添加到此目录:
└─cpp/
├─ googletest/
├─ CMakeLists.txt
├─ myfunctions.h
└─ mytests.cpp
- 打开您的
CMakeLists.txt 并输入以下内容:
cmake_minimum_required(VERSION 3.12) # version can be different
project(my_cpp_project) #name of your project
add_subdirectory(googletest) # add googletest subdirectory
include_directories(googletest/include) # this is so we can #include <gtest/gtest.h>
add_executable(mytests mytests.cpp) # add this executable
target_link_libraries(mytests PRIVATE gtest) # link google test to this executable
- 例如
myfunctions.h的内容:
#ifndef _ADD_H
#define _ADD_H
int add(int a, int b)
{
return a + b;
}
#endif
- 以
mytests.cpp为例子的内容:
#include <gtest/gtest.h>
#include "myfunctions.h"
TEST(myfunctions, add)
{
GTEST_ASSERT_EQ(add(10, 22), 32);
}
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
现在您只需运行测试即可。有多种方法可以做到这一点。
在终端中,在cpp/ 中创建一个build/ 目录:
mkdir build
您的目录现在应该如下所示:
└─cpp/
├─ build/
├─ googletest/
├─ CMakeLists.txt
├─ myfunctions.h
└─ mytests.cpp
接下来进入build目录:
cd build
然后运行:
cmake ..
make
./mytests
另一种方式:
- 为 VS Code 安装
CMake Tools 扩展
- 在底部栏中,您可以看到要构建/运行的当前目标(在方括号中Build [mytest] 和Run [mytest]):
- 然后只需单击运行按钮。
自行构建 Google 测试
使用终端:
- 进入目录
/home/user/Desktop/projects/cpp/googletest
- 在其中创建
build/,使其如下所示:
└─cpp/googletest/
├─ build/
├─ ...other googletest files
cd build
- 运行:
cmake -Dgtest_build_samples=ON -DCMAKE_BUILD_TYPE=Debug ..
make -j4
./googletest/sample1_unittest
使用 VS 代码
- 在 VS Code 中打开
googletest 文件夹
- CMake 扩展将提示配置,允许它
- 您将看到一个
.vscode 目录。里面是settings.json 文件,打开它,添加以下内容:
"cmake.configureSettings": { "gtest_build_samples": "ON" }
- 通过底部栏中的按钮构建和运行