前言
鴻蒙系統的代碼倉庫使用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/googletestmkdir 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成功