前言
鸿蒙系统的代码仓库使用GTest作为单元测试的工具。特性开发时,需要写demo以验证开发思路。因此有必要搭建GTest开发环境配合鸿蒙特性开发做开发demo。 我测试环境是wsl2 Ubuntu22.04 LTS。
搭建过程
安装必备C++组件
sudo apt install -y unzip g++ gcc cmake make automake
下载GTest
源码点这里
git clone https://github.com/google/googletest.git
如果网络不好,可以去下载发布版本1.17.0
unzip googletest-1.17.0.zip -d /home/tools/googletest
本地安装
cd /home/tools/googletest
mkdir build
cd build
cmake ..
make
sudo make install # 默认安装到 /usr/local/ 路径
验证
创建demo工程TestExample
目录结构:
root@DESKTOP-R500S71:/home/tmp/TestExample# tree -L 1
.
├── CMakeLists.txt
├── build
└── test_example.cpp
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(TestExample)
enable_testing()
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIRS})
add_executable(test_example test_example.cpp)
target_link_libraries(test_example ${GTEST_LIBRARIES} pthread)
add_test(NAME example_test COMMAND test_example)
test_example.cp
#include <gtest/gtest.h>
#include <iostream>
TEST(ADDTEST,ADDTEST_TRUE)
{
int num = 1;
EXPECT_EQ(num,1);
}
int main(int argc, char **argv) {
std::cout << "Running main() from test_example.cpp\n";
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
demo编译运行
cd /home/tmp/TestExample/
mkdir build
cmake ..
make
./test_example
运行结果
root@DESKTOP-R500S71:/home/tmp/TestExample/build# ./test_example
Running main() from test_example.cpp
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from ADDTEST
[ RUN ] ADDTEST.ADDTEST_TRUE
[ OK ] ADDTEST.ADDTEST_TRUE (0 ms)
[----------] 1 test from ADDTEST (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.
结论
ubuntu22.04安装gtest成功