gtest編寫第一個測試用例出錯及其解決過程
安裝好gtest後,編寫第一個測試案例test_main.cpp
#include <iostream>
#include <gtest/gtest.h>
using namespace std;
int Foo(int a,int b)
{
return a+b;
}
TEST(FooTest, ZeroEqual)
{
ASSERT_EQ(0,0);
}
TEST(FooTest, HandleNoneZeroInput)
{
EXPECT_EQ(12,Foo(4, 10));
EXPECT_EQ(6, Foo(30, 18));
}
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
按照gtest的介紹MakeFile文件為
TARGET=test_main
all:
gtest-config --min-version=1.0 || echo "Insufficient Google Test version."
g++ $(gtest-config --cppflags --cxxflags) -o $(TARGET).o -c test_main.cpp
g++ $(gtest-config --ldflags --libs) -o $(TARGET) $(TARGET).o
clean:
rm -rf *.o $(TARGET)
但是編譯的時候,出現錯誤
cxy-/home/chenxueyou/gtest$ make gtest-config --min-version=1.0 || echo "Insufficient Google Test version." g++ -o test_main.o -c test_main.cpp g++ -o test_main test_main.o test_main.o: In function `FooTest_ZeroEqual_Test::TestBody()': test_main.cpp:(.text+0x9e): undefined reference to `testing::internal::AssertHelper::AssertHelper(testing::TestPartResult::Type, char const*, int, char const*)' ...
省略了部分錯誤信息,看到了undefined reference,編譯通過,但是鏈接失敗,可以猜測是沒有找到對應的庫。再仔細看實際執行時打印的命令為
g++ -o test_main.o -c test_main.cpp
g++ -o test_main test_main.o
很顯然,沒有引入gtest的頭文件,也沒有加載gtest對應的庫。
執行命令 >echo $(gtest-config --cppflags --cxxflags)
和 echo $(gtest-config --ldflags --libs)
可以得到gtest配置的頭文件路徑和庫文件路徑。
cxy-/home/chenxueyou/gtest$ echo $(gtest-config --cppflags --cxxflags) -I/usr/include -pthread cxy-/home/chenxueyou/gtest$ echo $(gtest-config --ldflags --libs) -L/usr/lib64 -lgtest -pthread
而在我們的Makefile中執行時上麵兩個命令的結果為空。所以修改Makefile,手動指定頭文件路徑和庫文件路徑,Makefile為
TARGET=test_main
all:
gtest-config --min-version=1.0 || echo "Insufficient Google Test version."
g++ -I/usr/include -pthread -o $(TARGET).o -c test_main.cpp
g++ -L/usr/lib64 -lgtest -pthread -o $(TARGET) $(TARGET).o
clean:
rm -rf *.o $(TARGET)
這樣,我們的第一個gtest測試文件就能編譯通過了。
總結
1.Makefile實際執行的命令可能與預想的命令不一樣,要仔細查看。
2.gtest通過頭文件和庫的方式引入工程,要指定其頭文件和庫文件的位置
3.gtest-config命令能夠幫助我們找到對應的路徑
歡迎光臨我的網站----蝴蝶忽然的博客園----人既無名的專欄。
如果閱讀本文過程中有任何問題,請聯係作者,轉載請注明出處!
最後更新:2017-04-03 06:03:03