- 从Github下载google test源码
- 确保本地安装Visual Studio和CMake GUI,本次测试使用VS2017及Cmake GUI 3.20.5
- 解压googletest-main,打开Cmake GUI,配置源码路径(googletest-main路径),和生成路径(googletest-main/build),需要在生成路径下创建"build"文件夹,记得检查一下MSVC编译器路径在环境变量目录中
- 点击"Configure"按钮,在弹出的对话框中,选择"Specify the generator for this project" 为Visual Studio 15 2017编译器,"Option platform for generator(if empty, generator uses: Win32)"为x64,这里生成64位版本库,其他保持默认设置
bash
Selecting Windows SDK version 10.0.17763.0 to target Windows 10.0.19044.
The C compiler identification is MSVC 19.16.27045.0
The CXX compiler identification is MSVC 19.16.27045.0
Detecting C compiler ABI info
Detecting C compiler ABI info - done
Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional/VC/Tools/MSVC/14.16.27023/bin/Hostx86/x64/cl.exe - skipped
Detecting C compile features
Detecting C compile features - done
Detecting CXX compiler ABI info
Detecting CXX compiler ABI info - done
Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional/VC/Tools/MSVC/14.16.27023/bin/Hostx86/x64/cl.exe - skipped
Detecting CXX compile features
Detecting CXX compile features - done
Found Python3: D:/wecode_build_tools/mingw/bin/python3.8.exe (found version "3.8.2") found components: Interpreter
Looking for pthread.h
Looking for pthread.h - not found
Found Threads: TRUE
Configuring done
配置完毕后,在Configure上的选择框中,勾选"Build_SHRAED_LIBS",点击Configure按钮旁边的"Generate"按钮
bash
Selecting Windows SDK version 10.0.17763.0 to target Windows 10.0.19044.
Configuring done
Generating done
生成完毕后,点击"Generate"按钮旁边的"Open Project"按钮,打开VS build项目,选择"Release"/"x64"进行ALL_BUILD",生成完毕后,在"\googletest-main\build\bin\Release"目录下就会生成dll,在"、googletest-main\build\lib\Release"目录下生成lib,有了这些库,就可以创建GTest测试用例了,通常只需要"gtest/gtest_main"及"gmock/gmock_main"这4个dll/lib文件即可。
- 创建GTest测试用例:本次测试使用Visual Studio,使用CMake配合MinGW类型,只需要额外创建一个CMakeLists.txt即可。
创建一个VS console app程序,将googletest-main\include\gtest目录拷贝至项目目录下,添加到项目include path,拷贝gtest/gtest_main lib到项目目录下,添加到项目link目录和项;编写func.h/func.cpp作为待测试API,编写func_test.cpp作为单元测试,编写main程序如下:
main.cpp
cpp
#include "googletest/inc/gtest/gtest.h"
int main()
{
std::cout << "Hello GTest!\n";
::testing::InitGoogleTest();
return RUN_ALL_TESTS();
}
func_test.cpp
cpp
#include "googletest/inc/gtest/gtest.h"
#include "func.h"
TEST(func, add_test) {
int a = 1, b = 2;
int c = 3;
ASSERT_EQ(c, add(a, b));
}
func.h
cpp
int add(int a, int b);
func.cpp
cpp
#include "func.h"
int add(int a, int b) {
return a + b;
}
编译后,将gtest/gtest_main dll放在exe生成目录下,运行:
bash
Hello GTest!
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from func
[ RUN ] func.add_test
[ OK ] func.add_test (4607 ms)
[----------] 1 test from func (4608 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (4609 ms total)
[ PASSED ] 1 test.
可以为不同的代码模块创建不同的测试用例,放在独立的test.cpp文件中,所有的用例都会执行。