Search code examples
c++gccgoogletest

Pros and cons of having testable classes in header files instead of .cpp files when using gtest?


I'm taking over a project with gigantic gtest suite. I'm adding extra tests. The way it was setup before me is the following. All testable classes are in header files and are included in main.cpp(test suite runner). Problem is, that compiler runs out of memory while trying to compile main.cpp with a lot of included files. The "normal" way of doing it is to have test classes in separate files, since gtest finds test classes through macro expansion. Figured that gtest has some sort of singleton with subscribers going. Can someone explain to me why would previous maintainer had test classes in header files? Pros and Cons See a code example of having test classes in header files. // file ZondTest.hpp

class ZondTest : public ::testing::Test

{
public:
   static const std::string INPUT_FILES_DIR;
protected:
   virtual void SetUp() //runs this set up before every test
   {
      //might put something here later if I need to

   }
};
const std::string ZondTest::INPUT_FILES_DIR =
                     "InputFiles/ZondManagerTest/";

class TestableZond_c : public Zond_c
{
public :

   TestableZond_c()
   {
   }

   virtual ~TestableZond_c()
   {
   }
};

//check if newly created zond has empty space
TEST(ZondTest,
       WhenCreatedNewZondWithoutSpaceExpectEmptySpace)
{
   TestableZond_c mTestableZond = TestableZond_c();
   EXPECT_TRUE(mTestableZond.SpaceEmpty());
}
// a tone more tests
// ....

included in main.cpp.

#include "RD/ZM/ZondTest.hpp"
//many more includes
//........
int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Solution

  • One thing that I figured out is that if you are using Eclipse, indexer cannot find a way to tie files that googletest automatically finds. So your file looks messy with all squiggly underlines. But if you put TEST_P/TEST_F into header files and have them included in main. Eclipse indexer can "crawl" included files and build indexes and it looks pretty and gives false idea that it is the right way.