使用gtest时,在头文件中而不是.cpp文件中具有可测试类的利弊

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

本文关键字:文件 测试类 cpp gtest 使用      更新时间:2023-10-16

我正在接管一个拥有巨大gtest套件的项目。我正在增加额外的测试。在我之前,它的设置方式如下。所有可测试类都在头文件中,并包含在main.cpp(测试套件运行程序(中。问题是,编译器在试图编译包含大量文件的main.cpp时内存不足。"正常"的方法是将测试类放在单独的文件中,因为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类放在FnordTest.hpp而不是FnordTest.cpp中(会带来什么好处。。。

编译器(通常(不会为头创建对象文件,因此需要在main.cpp中包含所有.hpp文件,这可能会导致单个过大的编译单元,导致编译器内存不足(尤其是在考虑到谷歌测试的宏魔力时(。

我只能建议将测试放入.cpp文件中——这样你甚至不需要包含它们;谷歌测试自动找到你用test_P/test_F等声明的所有测试。

我发现的一件事是,如果您使用Eclipse,索引器无法找到一种方法来绑定谷歌测试自动找到的文件。所以你的文件看起来乱七八糟,下划线都是歪歪扭扭的。但如果您将TEST_P/TEST_F放入头文件中,并将它们包含在main中。Eclipse索引器可以"抓取"包含的文件并构建索引,它看起来很漂亮,而且会让人误以为这是正确的方法。