简体   繁体   English

如何有效地在 googletest 中组织单元测试

[英]How to organize unit tests in googletest efficiently

I am currently thinking about restructuring the unit tests in my project.我目前正在考虑在我的项目中重组单元测试。 I use Googletest as testing framework.我使用 Googletest 作为测试框架。 My project consists of several shared libraries that are built and tested together.我的项目由几个共同构建和测试的共享库组成。

As the number of unit tests grow, I find the organization of unit tests in google test getting harder and harder because I include a ton of header files where the tests live.随着单元测试数量的增加,我发现 google test 中单元测试的组织变得越来越难,因为我在测试所在的地方包含了大量的 header 文件。 This leads to a huge object size while building the project and I already had to switch on big object compilation , to make the build succeed.这导致在构建项目时 object 大小很大,我已经不得不打开大的 object 编译,以使构建成功。

Think of the project structure like shown below考虑如下所示的项目结构

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

And my main.cpp looking something like this:我的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();
}

I really want to have some kind of modularization here, where I can split the code in a way, that I end up having separate compilation units for the different modules, so that I do not have this ugly big object compilation issue, however I have no clue what's the correct way to do that with googletest, where all those test macros have to be present in header files.我真的很想在这里进行某种模块化,在这里我可以以某种方式拆分代码,最终为不同的模块提供单独的编译单元,这样我就没有这个丑陋的大 object 编译问题,但是我有不知道使用 googletest 的正确方法是什么,所有这些测试宏都必须存在于 header 文件中。

Can anyone share some advice?任何人都可以分享一些建议吗?

If you look at the samples provided in the sources , the test macros shouldn't be present in header files.如果您查看源中提供的示例,测试宏不应该出现在 header 文件中。 According to this answer :根据这个答案

The RUN_ALL_TESTS() macro run all instances of test class dynamically, which means it got the test cases during run time. RUN_ALL_TESTS() 宏动态运行测试 class 的所有实例,这意味着它在运行时获取了测试用例。

So basically, your main should include only the gtest headers, and your tests should be in.cpp files, with every test only including the libs that you need.所以基本上,你的 main 应该只包括 gtest 头文件,你的测试应该是 in.cpp 文件,每个测试只包括你需要的库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM