您的位置:首页 > 其它

gtest编写第一个测试用例出错及其解决过程

2014-06-27 09:51 288 查看
安装好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命令能够帮助我们找到对应的路径

欢迎光临我的网站----蝴蝶忽然的博客园----人既无名的专栏

如果阅读本文过程中有任何问题,请联系作者,转载请注明出处!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: