gtest单元测试工具

环境搭建

gtest下载地址: https://github.com/google/googletest
下载方法是:git clone https://github.com/google/googletest.git

安装方法是:

$ cd googletest

注意:如果在make 过程中报错,可在CMakeLists.txt 中增加如下行,再执行下面的命令:  SET(CMAKE_CXX_FLAGS "-std=c++11")  
$ cmake .    
$ make
然后在lib目录下会生成:libgmock.a libgmock_main.a libgtest.a libgtest_main.a
最后我们再sudo make install。

不需要自己写mian

g++ sample1.cc sample1_unittest.cc -lgtest -std=c++11 -lgtest_main -lpthread -o test1
#include "sample1.h"

// 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;
}

// Returns true iff n is a prime number.
bool IsPrime(int n) {
  // Trivial case 1: small numbers
  if (n <= 1) return false;

  // Trivial case 2: even numbers
  if (n % 2 == 0) return n == 2;

  // Now, we have that n is odd and n >= 3.

  // Try to divide n by every odd number i, starting from 3
  for (int i = 3; ; i += 2) {
    // We only have to try i up to the square root of n
    if (i > n/i) break;

    // Now, we have i <= n/i < n.
    // If n is divisible by i, n is not prime.
    if (n % i == 0) return false;
  }

  // n has no integer factor in the range (1, n), and thus is prime.
  return true;
}
//这两个函数定义在sample1.cc文件里,函数申明在sample1.h里:
#ifndef GTEST_SAMPLES_SAMPLE1_H_
#define GTEST_SAMPLES_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 

自写测试用例

#include 
#include "sample1.h"
#include "gtest/gtest.h"
namespace {

	TEST(FactorialTest, Negative) {//测试对于复数得场景
	    // This test is named "Negative", and belongs to the "FactorialTest"
	    // test case.
	    EXPECT_EQ(1, Factorial(-5));//断言测试 参数1 断言返回是多少 参数2函数并带参数
	    EXPECT_EQ(1, Factorial(-1));
	    EXPECT_GT(Factorial(-10), 0);
	}
	
	TEST(FactorialTest, Zero) {//测试对正数得场景
	    EXPECT_EQ(1, Factorial(0));
	}
	
	TEST(FactorialTest, Positive) {
	    EXPECT_EQ(1, Factorial(1));
	    EXPECT_EQ(2, Factorial(2));
	    EXPECT_EQ(6, Factorial(3));
	    EXPECT_EQ(40320, Factorial(8));
	}
	
	// Tests IsPrime()
	TEST(IsPrimeTest, Negative) {
	  EXPECT_FALSE(IsPrime(-1));
	  EXPECT_FALSE(IsPrime(-2));
	  EXPECT_FALSE(IsPrime(INT_MIN));
	}
	
	TEST(IsPrimeTest, Trivial) {
	  EXPECT_FALSE(IsPrime(0));//返回得是假
	  EXPECT_FALSE(IsPrime(1));
	  EXPECT_TRUE(IsPrime(2));//返回得是真
	  EXPECT_TRUE(IsPrime(3));
	}
	
	TEST(IsPrimeTest, Positive) {
	  EXPECT_FALSE(IsPrime(4));
	  EXPECT_TRUE(IsPrime(5));
	  EXPECT_FALSE(IsPrime(6));
	  EXPECT_TRUE(IsPrime(23));
	}
}  // namespace
TEST是gtest的测试宏,我们的测试用例必须按照这样格式写,
isPrimeTest是测试套的名字,一个测试套下可以有多个测试用例,
那么Positive、Trivial就是我们测试用例的名称,EXPECT_EQ、EXPECT_FALSE
和EXPECT_TRUE等等,都是gtest提供的测试断言,比如 EXPECT_EQ(1, Factorial(1));
就是表示Factorial(1)1是不是相等的,如果是则表示EXPECT_EQ会返回成功,否则失败
,也即我们测试用例会失败或者成功。

你可能感兴趣的:(笔记,c++)