安装好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相应的库。