文章目录
下载googletest
Release v1.14.0 · google/googletest · GitHub
将googletest解压到项目目录并创建build文件夹
在googletest目录中创建build文件夹
编译googletest
在build文件夹下打开powershell,执行以下命令进行编译
cmake .. -G "MinGW Makefile"
# 如果不行也可以执行下面的命令
# cmake .. -G "Visual Studio 17 2022"
cmake --build .
编译完成后会在build文件夹下生成若干文件
在项目的CMakeLists.txt文件中添加相关依赖
项目结构如图所示:
使用的CMakeLists.txt文件如下:
cmake_minimum_required(VERSION 3.25)
project(CppLearnAndTest)
set(CMAKE_CXX_STANDARD 23)
# 添加googletest子目录
add_subdirectory(googletest-1.14.0)
# 指定可执行文件的产生路径
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/cmake-build-debug)
# gtest 头文件
include_directories(googletest-1.14.0/googletest/include)
# gmock 头文件
include_directories(googletest-1.14.0/googlemock/include)
# 指定静态链接文件目录
link_directories(${PROJECT_SOURCE_DIR}/googletest-1.14.0/build/lib/Debug)
# 构建可执行文件
add_executable(CppLearnAndTest leetcode/easy/lc1/lc1.cpp)
# 设置依赖并执行链接
set(GTEST_LIBS gtest gmock gtest_main gmock_main pthread)
target_link_libraries(CppLearnAndTest ${GTEST_LIBS})
其中的文件路径要按实际情况处理。
编写测试并执行
以两数之和为例,完整文件如下
#include "gtest/gtest.h"
#include "vector"
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {};
}
};
TEST(lc1, test_1) {
vector<int> input = {2,7,11,15};
int target = 9;
vector<int> ret = {0,1};
Solution s = Solution();
EXPECT_EQ(ret, s.twoSum(input, target));
}
TEST(lc1, test_2) {
vector<int> input = {3,2,4};
int target = 6;
vector<int> ret = {1,2};
Solution s = Solution();
EXPECT_EQ(ret, s.twoSum(input, target));
}
TEST(lc1, test_3) {
vector<int> input = {3,3};
int target = 6;
vector<int> ret = {0,1};
Solution s = Solution();
EXPECT_EQ(ret, s.twoSum(input, target));
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
参考
googletest windows平台安装使用_window安装googletest build type-CSDN博客
windows从零搭建googlemock之c++测试工程(CLion)_gmock多线程-CSDN博客
使用 cmake 对 googletest 的依赖问题:gtest/gtest.h 没有这样的文件或目录答案 - 爱码网 (likecs.com)
标签:vector,target,windows,C++,int,gtest,googletest,build From: https://blog.csdn.net/lnluozi/article/details/140236000