试用 googltest C++ 测试框架
Google Test 是非常好用的 C++ 测试框架
从 http://code.google.com/p/googletest/ 下载 gtest,把源文件放在项目的src目录中,把头文件放在gtest目录中,
在工程的目录选项中加gtest目录到头文件搜索路径中,比如eclipse中设置 -I "${workspace_loc:/gtest/src}"
测试代码如下:
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
int Factorial(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
#include "src/gtest-all.cc"
// Tests Factorial().
// Tests factorial of negative numbers.
TEST(FactorialTest, Negative)
{
EXPECT_EQ(1, Factorial(-5));
EXPECT_EQ(1, Factorial(-1));
EXPECT_TRUE(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));
}
#include "src/gtest_main.cc"
int Factorial(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
#include "src/gtest-all.cc"
// Tests Factorial().
// Tests factorial of negative numbers.
TEST(FactorialTest, Negative)
{
EXPECT_EQ(1, Factorial(-5));
EXPECT_EQ(1, Factorial(-1));
EXPECT_TRUE(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));
}
#include "src/gtest_main.cc"
运行结果为:
Running main() from gtest_main.cc
[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 3 tests from FactorialTest
[ RUN ] FactorialTest.Negative
[ OK ] FactorialTest.Negative
[ RUN ] FactorialTest.Zero
[ OK ] FactorialTest.Zero
[ RUN ] FactorialTest.Positive
[ OK ] FactorialTest.Positive
[----------] Global test environment tear-down
[==========] 3 tests from 1 test case ran.
[ PASSED ] 3 tests.
[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 3 tests from FactorialTest
[ RUN ] FactorialTest.Negative
[ OK ] FactorialTest.Negative
[ RUN ] FactorialTest.Zero
[ OK ] FactorialTest.Zero
[ RUN ] FactorialTest.Positive
[ OK ] FactorialTest.Positive
[----------] Global test environment tear-down
[==========] 3 tests from 1 test case ran.
[ PASSED ] 3 tests.