c/c++测试框架gtest
日期:2015-07-15 10:36:07
最后更新日期:2015-07-28 16:32:32
1.下载gtest的源码包
2.编译安装
阅读README或
./configure
make all
该步骤后会生成头文件,但库文件是libgtest.la格式,若需要.a格式,那么在源码目录执行:
[code lang="cpp"]
g++ -isystem ./include/ -I./ -c src/gtest-all.cc
g++ -isystem ../include/ -I./ gtest_main.cc -c
ar -rv libgtest.a gtest-all.o
ar -rv libgtest.a gtest_main.o
[/code]
3.使用
源码的samples目录有一系列的单元测试例子,如sample1_unittest.cc 为 sample1.cc 的单元测试文件。如注释所说,使用gtest只需要1-2-3步
第1步:包含头文件,sample1.h为sample1.cc接口申明
[code lang="cpp"]
#include <limits.h>
#include "sample1.h"
#include "gtest/gtest.h"
[/code]
第2步: 在你的单元测试里面使用框架提供的TEST macro,完整的TEST macro见gtest.h头文件。单元测试应该是完备的,如测试阶乘包含了负数,0,正数的单元测试:
[code lang="cpp"]
// Tests Factorial()
// Tests factorial of negative numbers.
TEST(FactorialTest, Negative) {
EXPECT_EQ(1, Factorial(-5));
EXPECT_EQ(1, Factorial(-1));
EXPECT_GT(Factorial(-10), 0);
}
// Tests factorial of 0.
TEST(FactorialTest, Zero) {
EXPECT_EQ(1, Factorial(0));
}
// Tests factorial of positive numbers.
TEST(FactorialTest, Positive) {
EXPECT_EQ(1, Factorial(1));
EXPECT_EQ(2, Factorial(2));
EXPECT_EQ(6, Factorial(3));
EXPECT_EQ(40320, Factorial(8));
}
[/code]
第3步: 在main函数里面调用RUN_ALL_TESTS()。
实际上src/gtest_main.cc里面会调用RUN_ALL_TESTS(),若直接链接libgtest.a库或gtest_main.o,则不必这步。
后面再研究下C++类的测试,做到类类型测试其行为如内置类型一样。
samples/sample2_unittest.cc
[code lang="cpp"]
// Tests the default c'tor.
TEST(MyString, DefaultConstructor) {
const MyString s;
EXPECT_STREQ(NULL, s.c_string());
EXPECT_EQ(0u, s.Length());
}
const char kHelloString[] = "Hello, world!";
// Tests the c'tor that accepts a C string.
TEST(MyString, ConstructorFromCString) {
const MyString s(kHelloString);
EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1,
s.Length());
}
// Tests the copy c'tor.
TEST(MyString, CopyConstructor) {
const MyString s1(kHelloString);
const MyString s2 = s1;
EXPECT_EQ(0, strcmp(s2.c_string(), kHelloString));
}
// Tests the Set method.
TEST(MyString, Set) {
MyString s;
s.Set(kHelloString);
EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
// Set should work when the input pointer is the same as the one
// already in the MyString object.
s.Set(s.c_string());
EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
// Can we set the MyString to NULL?
s.Set(NULL);
EXPECT_STREQ(NULL, s.c_string());
}
[/code]