使用gtest时,在头文件中而不是.cpp文件中具有可测试类的利弊
Pros and cons of having testable classes in header files instead of .cpp files when using gtest?
我正在接管一个拥有巨大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索引器可以"抓取"包含的文件并构建索引,它看起来很漂亮,而且会让人误以为这是正确的方法。
相关文章:
- 命名空间中具有.h和.cpp文件的类
- C++头文件和类实现出现问题
- 如何访问头文件中类的组件并打印它们的地址?
- 如何从另一个文件调用类构造函数?
- 使用gtest时,在头文件中而不是.cpp文件中具有可测试类的利弊
- googlemock-如何模拟被测试类所拥有的对象
- 为什么它无法在 c++ 中全局声明一个构建为 dll 文件的类?
- 单元测试类无法在我要测试的同一解决方案中的另一个项目中找到类
- 不同文件的类,如何使其工作?
- 如何在另一个文件的类中声明函数
- 在单独的文件中类
- 错误:当定义两个带有标头文件的类时,将重新定义类
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- 无法显示文件(与类有关)
- gmock EXPECT_CALL 不会在测试类中调用该方法
- 使用专业化来测试类中值的存在
- Visual Studio单元使用具有相对路径的文件测试
- 如何让头文件知道类继承
- 如何根据头文件中定义的代码测试类
- 如何在Google test中使用.c文件来编写测试类而不是.cpp文件