gtest

1.windows上使用vcpkg下载gtest动态库与静态库

1.gtest动态库

1
.\vcpkg.exe install gtest:x64-windows

2.下载安装git bash环境

2.cmake使用vcpkg管理的raylib库

1.项目结构

1
2
3
4
│  build.sh
│ CMakeLists.txt
│ test_example.cpp

2.test_example.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <gtest/gtest.h>
#include <iostream>

// 对应 TEST_MODULE_INITIALIZE:GTest 使用全局环境或简单的函数
// 如果只是打印,可以直接在测试用例里写,或者使用下面的全局环境
class MyEnvironment : public ::testing::Environment {
public:
void SetUp() override {
std::cout << "初始化测试模块 (GTest Global SetUp)" << std::endl;
}
};

// 注册全局环境(可选)
auto* const env = ::testing::AddGlobalTestEnvironment(new MyEnvironment);

// 对应 TEST_METHOD(TestAddition)
// 语法:TEST(测试套件名, 测试用例名)
TEST(ExampleTest, TestAddition) {
// 对应 Assert::AreEqual(3, 1 + 2)
EXPECT_EQ(3, 1 + 2);
}

// 对应 TEST_METHOD_CLEANUP
// 如果需要每个测试用例后清理,可以使用类(Fixture)
class ExampleTestFixture : public ::testing::Test {
protected:
void TearDown() override {
// 这里写清理逻辑
// std::cout << "清理资源..." << std::endl;
}
};

// 使用 Fixture 的写法
TEST_F(ExampleTestFixture, TestWithCleanup) {
ASSERT_TRUE(true);
}

3.CMakeLists.txt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 启用 CTest
enable_testing()

# 寻找 GTest (由 vcpkg 提供)
find_package(GTest CONFIG REQUIRED)

# 你的测试源码
add_executable(unit_tests "test_example.cpp")

target_compile_features(unit_tests PRIVATE cxx_std_20)

# 链接 GTest
# gtest_main 会自动提供 main(),你不需要在 cpp 里写 main
target_link_libraries(unit_tests PRIVATE GTest::gtest_main GTest::gtest)

# 自动发现测试用例
include(GoogleTest)
gtest_discover_tests(unit_tests)

4.build.sh

文件编码为utf-8

1
2
3
4
5
6
7
8
9
10
11
12
# 1. 创建并进入构建目录
mkdir build
cd build

# 2. 配置项目 (加上 vcpkg 工具链路径)
cmake .. -DCMAKE_TOOLCHAIN_FILE="C:/D/test/CC++/cc++lib/vcpkg/vcpkg/scripts/buildsystems/vcpkg.cmake"

# 3. 编译
cmake --build .

# 4. 运行测试 (使用 ctest)
ctest

使用git bash环境运行build.sh