使用 gtest 时,在头文件而不是 .cpp 文件中具有可测试 类 的优缺点?

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

我正在接手一个带有巨大 gtest 套件的项目。我正在添加额外的测试。在我之前设置的方式如下。所有可测试的 类 都在头文件中,并包含在 main.cpp(测试套件运行程序)中。 问题是,编译器在尝试使用大量包含的文件编译 main.cpp 时内存不足。 "normal" 的做法是将测试 类 放在单独的文件中,因为 gtest 通过宏扩展找到测试 类。认为 gtest 有某种单例,订阅者正在运行。 有人可以向我解释为什么以前的维护者会在头文件中测试 类 吗?优点和缺点 请参阅在头文件中进行测试 类 的代码示例。 // 文件 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
// ....

包含在 main.cpp 中。

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

我不确定将测试用例放在 .hpp 文件而不是 .cpp 文件中有什么好处(即将 FnordTest class 放在 FnordTest.hpp 而不是 FnordTest.cpp ) 应该带...

编译器(通常)不会为头文件创建目标文件,因此需要将所有这些 .hpp 文件包含在您的 main.cpp 中,这可能会导致单个编译单元过大,从而导致你的编译器 - 正如你所说 - 运行 内存不足(尤其是考虑到 googletest 的宏魔法时)。

我只能建议将测试放入 .cpp 文件中——这样您甚至不需要包含它们; googletest 会自动找到您用 TEST_P/TEST_F 等

声明的所有测试

我发现的一件事是,如果您使用的是 Eclipse,索引器无法找到绑定 googletest 自动找到的文件的方法。所以你的文件看起来很乱,所有的下划线都是波浪形的。但是如果你将 TEST_P/TEST_F 放入头文件并将它们包含在 main.h 中。 Eclipse 索引器可以 "crawl" 包含文件和构建索引,它看起来很漂亮,但让人误以为这是正确的方法。