leon22
leon22

Reputation: 5649

GoogleTest several C++ projects in the same solution

I have e.g. 10 C++ projects in a solution SolA and want to UnitTest them with GoogleTest:

so I created a new solution SolATest and for every project of SolA an unit test project in SolATest!

Is it a good approach to load the SolA libraries implicit in SolATest/Projects and run every test project as an executable:

#include <iostream>
#include "gmock/gmock.h"
#include "gtest/gtest.h"

int main(int argc, char **argv) 
{   
    ::testing::InitGoogleMock(&argc, argv); 
    int value = RUN_ALL_TESTS();

    std::getchar(); // to hold the terminal open

    return value;
}

or is there a more convenience way -> e.g. only have one executable in SolATest and load the other test projects as libraries (IMHO to have all cpp files in one test project is confusing)?!

Thx for any help

Upvotes: 1

Views: 1721

Answers (1)

Ian
Ian

Reputation: 872

Either approach should work; it just depends on your preference. I tend to follow a project structure like the following:

Solution
 |-- ProjectA 
 |-- ProjectATests
 |-- ProjectB
 |-- ProjectBTests
 `-- TestLib

Where the projects (ProjectA, ProjectB) are libraries, and each test project (ProjectATests, ProjectBTests) is an executable. Note that we do not separate unit tests into a separate solution; they are always built and run alongside the production code. I like this structure for a few reasons:

  1. It's easier to run just the tests that are related to your changes.
  2. The development workflow is a bit more efficient, since when making changes to one library you only have to rebuild and link the corresponding test.

Whether you create a single test project or multiple, I would definitely recommend putting the project in the same solution as the code under test. Further, I would recommend setting up a post-build step for the test project(s) which runs the tests and fails the build if they don't pass.

Lastly, you might be wondering about that 'TestLib' project. I use that for the gtest/gmock fused sources, the definition of main(), and any other utilities that are shared between tests. That eliminates (or at least, reduces) code duplication between the various test projects.

Upvotes: 5

Related Questions