Qt项目中集成使用Google Test单元测试模块

Google Test的下载安装

  • 下载googletest完成后解压
    下载地址:https://github.com/google/googletest

  • 利用QtCreator自动生成googletest的pri项目依赖文件
      由于我们要集成到Qt项目中,需要把googletest集成进来,需要自己编写一个pri文件,然后依赖到自己的Qt项目中,其实QtCreator已经可以自动生成googletest的pri文件,无需手动操作了。步骤如下:

  1. 新建测试工程。
    在这里插入图片描述
  2. 配置工程,选择好googletest目录。
    在这里插入图片描述
  3. 工程生成完成后,会在工程目录下生成gtest_dependency.pri的pri文件。把此文件拷贝到googletest-master的目录下面去。该文件即为自动生成的googletest的依赖文件,其他项目包含集成此文件即可使用googletest。不过使用前需要稍微进行修改,
    在这里插入图片描述
    在这里插入图片描述
  • 其他项目工程引用
    我们只有在其他工程的.pro文件中引入gtest_dependency.pri文件即可。注意include的路径,根据自己的路径进行修改。
include(./googletest-master/gtest_dependency.pri)

然后在main.cpp中包含头文件即可使用googletest进行单元测试。

#include "mainwindow.h"
#include <QApplication>

#include <gtest/gtest.h>
#include <gmock/gmock-matchers.h>
using namespace testing;

int Factorial(int n)
{
    int result = 1;
    for (int i = 1; i <= n; i++)
    {
        result *= i;
    }

    return result;
}

TEST(Factorial, Empty)
{
    EXPECT_EQ(1, Factorial(1));
}

int main(int argc, char *argv[])
{
    QHxApplication a(argc, argv);
    ::testing::InitGoogleTest(&argc, argv); //googleTest框架
    
    MainWindow w;
    w.show();

    RUN_ALL_TESTS();//googleTest框架
    return a.exec();
}

可以通过QtCreator下面的测试结果界面运行并查看单元测试结果。
在这里插入图片描述

googletest基本用法:
【基本断言】:

Fatal assertion Nonfatal assertion Verifies
ASSERT_TRUE(condition) EXPECT_TRUE(condition) condition is true
ASSERT_FALSE(condition) EXPECT_FALSE(condition) condition is false

【二元断言】:

Fatal assertion Nonfatal assertion Verifies
ASSERT_EQ(val1, val2); EXPECT_EQ(val1, val2); val1 == val2
ASSERT_NE(val1, val2); EXPECT_NE(val1, val2); val1 != val2
ASSERT_LT(val1, val2); EXPECT_LT(val1, val2); val1 < val2
ASSERT_LE(val1, val2); EXPECT_LE(val1, val2); val1 <= val2
ASSERT_GT(val1, val2); EXPECT_GT(val1, val2); val1 > val2
ASSERT_GE(val1, val2); EXPECT_GE(val1, val2); val1 >= val2

【字符串断言】:

Fatal assertion Nonfatal assertion Verifies
ASSERT_STREQ(str1, str2); EXPECT_STREQ(str1, str2); the two C strings have the same content
ASSERT_STRNE(str1, str2); EXPECT_STRNE(str1, str2); the two C strings have different contents
ASSERT_STRCASEEQ(str1, str2); EXPECT_STRCASEEQ(str1, str2); the two C strings have the same content, ignoring case
ASSERT_STRCASENE(str1, str2); EXPECT_STRCASENE(str1, str2); the two C strings have different contents, ignoring case
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章