【问题标题】:How to organize unit tests in googletest efficiently如何有效地在 googletest 中组织单元测试
【发布时间】:2021-03-12 09:41:39
【问题描述】:

我目前正在考虑在我的项目中重组单元测试。我使用 Googletest 作为测试框架。我的项目由几个共同构建和测试的共享库组成。

随着单元测试数量的增加,我发现 google 测试中单元测试的组织变得越来越困难,因为我在测试所在的位置包含了大量的头文件。这会在构建项目时导致对象很大,我已经不得不打开大对象编译,以使构建成功。

考虑如下所示的项目结构

root
├── src
│   └── libs
|       ├── libA
|       ├── libB
|       ├── ....
│       └── libN   
└── tests
    └── unit_tests
        ├── libA
        |   ├──tst_group1.h
        |   ├──tst_group2.h
        |   └──tst_group3.h
        ├── libB
        |   ├──tst_group1.h
        |   ├──tst_group2.h
        |   └──tst_group3.h
        ├── ....
        ├── libN
        └── main.cpp

而我的main.cpp 看起来像这样:

#include "libA/tst_group1.h"
#include "libA/tst_group2.h"
#include "libA/tst_group3.h"
#include "libB/tst_group1.h"
#include "libB/tst_group2.h"
#include "libB/tst_group3.h"
[...]
#include <gmock/gmock-matchers.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>

int main(int argc, char* argv[])
{
    :testing::InitGoogleMock(&argc, argv);
    ::testing::InitGoogleTest();
    return RUN_ALL_TESTS();
}

我真的很想在这里进行某种模块化,在这里我可以以某种方式拆分代码,最终为不同的模块提供单独的编译单元,这样我就没有这个丑陋的大对象编译 问题,但是我不知道使用 googletest 的正确方法是什么,所有这些测试宏都必须存在于头文件中。

谁能分享一些建议?

【问题讨论】:

    标签: c++ unit-testing googletest code-organization project-structure


    【解决方案1】:

    如果您查看the samples provided in the sources,则测试宏不应出现在头文件中。 根据this answer

    RUN_ALL_TESTS() 宏动态运行测试类的所有实例,这意味着它在运行时获取了测试用例。

    所以基本上,你的 main 应该只包含 gtest 头文件,你的测试应该在 .cpp 文件中,每个测试只包含你需要的库。

    【讨论】:

      猜你喜欢
      • 2012-12-25
      • 2022-08-17
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 2013-02-04
      相关资源
      最近更新 更多