要在Ubuntu中使用gtest編寫測試用例,首先需要安裝gtest庫。可以通過以下命令安裝:
sudo apt-get install libgtest-dev
cd /usr/src/gtest
sudo cmake .
sudo make
sudo cp *.a /usr/lib
接下來,創建一個新的測試文件(例如test.cpp)并編寫測試用例。以下是一個簡單的示例:
#include <gtest/gtest.h>
TEST(MathTest, Addition) {
EXPECT_EQ(2 + 2, 4);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
將測試用例編譯成可執行文件:
g++ test.cpp -lgtest -lgtest_main -pthread -o test
最后,運行測試用例:
./test
如果所有測試用例都通過,將會輸出以下結果:
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from MathTest
[ RUN ] MathTest.Addition
[ OK ] MathTest.Addition (0 ms)
[----------] 1 test from MathTest (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[ PASSED ] 1 test.