gtest 学习之二测试函数功能
这是一个使用gtest测试框架的简单例子, 是gtest中给出的例子,用于测试函数的功能。
头文件sample1.h
#ifndef GTEST_SAMPLE1_H_ #define GTEST_SAMPLE1_H_ // Returns n! (the factorial of n). For negative n, n! is defined to be 1. int Factorial(int n); // Returns true iff n is a prime number. bool IsPrime(int n); #endif // GTEST_SAMPLE1_H_
实现文件sample1.cpp
#include "sample.h" // 返回 n! (the factorial of n). 对于负数, n! 被定义为 1. int Factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } // 如果是素数则返回 true bool IsPrime(int n) { // Trivial case 1: 小于1的数 if (n <= 1) return false; // Trivial case 2: 偶数 if (n % 2 == 0) return n == 2; // 当n是倚数且n > 3时 // 试着从3开始用倚数去除n for (int i = 3; ; i += 2) {
// 只有试到n的平方根即可 if (i > n/i) break; //如果能被i整除则不是素数. if (n % i == 0) return false; } //n不能被(1~n)范围内的数整除 return true; }
main.cpp中的代码:
#include "gtest/gtest.h" #include "sample.h" TEST(FactorialTest, Negative) { // This test is named "Negative", and belongs to the "FactorialTest" // test case. 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)); } // Tests negative input. TEST(IsPrimeTest, Negative) { // This test belongs to the IsPrimeTest test case. EXPECT_FALSE(IsPrime(-1)); EXPECT_FALSE(IsPrime(-2)); EXPECT_FALSE(IsPrime(INT_MIN)); } // Tests some trivial cases. TEST(IsPrimeTest, Trivial) { EXPECT_FALSE(IsPrime(0)); EXPECT_FALSE(IsPrime(1)); EXPECT_TRUE(IsPrime(2)); EXPECT_TRUE(IsPrime(3)); } // Tests positive input. TEST(IsPrimeTest, Positive) { EXPECT_FALSE(IsPrime(4)); EXPECT_TRUE(IsPrime(5)); EXPECT_FALSE(IsPrime(6)); EXPECT_TRUE(IsPrime(23)); } int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
编译后的运行结果: