Google Test

1. https://github.com/google/googletest/releases

2. 配置Google Test项目

  1)【解决方案】下右键,新建【GoogleTest项目】(Win32 Project)

  2)  解压gtest-1.7.0后,复制文件夹到【GoogleTest项目】

  3)  导入gtest头文件

    

  4) 右键【GoogleTest项目】 --> Add --> 现有项(gtest/src/gtest_main.cc、gtest-all.cc)

  5) 右键【GoogleTest项目】--> Build 

3. 创建单元测试项目

  1)【解决方案】下右键,新建【UnitTest项目】(Win32 Console Application)

  2) 导入头文件

    

  3) 为UnitTest项目添加引用

    


类源码

func.cpp

 1 #include "func.h"
 2 
 3 int fac(int nInput)
 4 {
 5     if (nInput < 0) {
 6         return -1;
 7     }
 8 
 9     int nRev = 1;
10     for (int i = 1; i <= nInput; ++i) {
11         nRev *= i;
12     }
13     return nRev;
14 }
15 
16 bool IsPrime(int n)
17 {
18     // Trivial case 1: small numbers
19     if (n <= 1) return false;
20 
21     // Trivial case 2: even numbers
22     if (n % 2 == 0) return n == 2;
23 
24     // Now, we have that n is odd and n >= 3.
25 
26     // Try to divide n by every odd number i, starting from 3
27     for (int i = 3; ; i += 2) {
28         // We only have to try i up to the squre root of n
29         if (i > n / i) break;
30 
31         // Now, we have i <= n/i < n.
32         // If n is divisible by i, n is not prime.
33         if (n % i == 0) return false;
34     }
35     // n has no integer factor in the range (1, n), and thus is prime.
36     return true;
37 }


func.h

 1 #pragma once
 2 #ifndef FUNC_C
 3 #define FUNC_C
 4 
 5 #ifdef __cplusplus
 6 extern "C"
 7 {
 8 #endif
 9     int fac(int nInput);
10     bool IsPrime(int n);
11 #ifdef __cplusplus
12 }
13 
14 #endif
15 
16 #endif //FUNC_C

Unit_test

unit_func.cpp

 1 // UnitTest01.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <limits>
 6 #include "func.h"
 7 #include "gtest/gtest.h"
 8 
 9 
10 TEST(test_func, fac_001)
11 {
12     EXPECT_EQ(-1, fac(-1));
13 }
14 
15 TEST(IsPrimeTest, HandleTrueReturn)
16 {
17     EXPECT_TRUE(IsPrime(3));
18     EXPECT_TRUE(IsPrime(5));
19     EXPECT_TRUE(IsPrime(11));
20     EXPECT_TRUE(IsPrime(23));
21     EXPECT_TRUE(IsPrime(17));
22 }
23 
24 
25 class IsPrimeParamTest : public::testing::TestWithParam<int>
26 {
27 
28 };
29 
30 INSTANTIATE_TEST_CASE_P(TrueReturn, IsPrimeParamTest, testing::Values(3, 5, 11, 23, 17, 11));
31 
32 TEST_P(IsPrimeParamTest, HandleTrueReturn)
33 {
34     int n = GetParam();
35     EXPECT_TRUE(IsPrime(n));
36 }


unit_func.h

 1 #pragma once
 2 #ifndef FUNC_C
 3 #define FUNC_C
 4 
 5 #ifdef __cplusplus
 6 extern "C"
 7 {
 8 #endif
 9     int fac(int nInput);
10 
11     #idef __cplusplus
12 }
13 
14 #endif
15 
16 #endif //FUNC_C
原文地址:https://www.cnblogs.com/xinzi7/p/7225418.html