我想运行样本测试并调试Google Test project。我在Ubuntu 16.04 LTS上使用VS Code。
/home/user/Desktop/projects/cpp/googletest
和mybuild
处创建了一个名为/home/user/Desktop/projects/cpp/mybuild
的新目录。 cmake -Dgtest_build_samples=ON /home/user/Desktop/projects/cpp/googletest
命令来构建项目,这生成了一堆文件,显然构建成功。 现在,我有两个问题:
最佳答案
/home/user/Desktop/projects/cpp/ # your project lives here
└─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();
}
现在,您只需要运行测试。有多种方法可以做到这一点。在终端中,在
build/
中创建一个cpp/
目录:mkdir build
您的目录现在应如下所示:└─cpp/
├─ build/
├─ googletest/
├─ CMakeLists.txt
├─ myfunctions.h
└─ mytests.cpp
接下来进入build
目录:cd build
然后运行:cmake ..
make
./mytests
替代方式:CMake Tools
扩展自行构建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代码
googletest
文件夹打开到VS Code .vscode
目录。在其中是settings.json
文件,将其打开,然后添加以下内容: "cmake.configureSettings": { "gtest_build_samples": "ON" }