Search code examples
c++unit-testinggoogletestcode-organizationproject-structure

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. 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. 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.

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:

#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.

Can anyone share some advice?


Solution

  • If you look at the samples provided in the sources, the test macros shouldn't be present in header files. 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.

    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.