[英]How to understand “implementations of virtual constructors” in Effective C++
[英]How to test several interface implementations with different constructors with gtest in C++?
我有一個接口,我有三個實現。 我正在使用來自 google 測試的 TYPED_TEST,以便我可以對所有實現使用相同的測試集。 我有以下夾具。
template <typename T>
class GenericTester : public ::testing::Test {
protected:
T test_class;
};
我在下面添加了實現類型。
using TestTypes = ::testing::Types<ImplementationOne, ImplementationTwo>
TYPED_TEST_SUITE(GenericDiffTester, DiffTypes);
到目前為止,一切正常,但現在我添加了另一個實現。 最后一個實現的區別在於它的構造函數需要一個std::string
作為參數,而前兩個可以默認構造。
現在,當我添加第三個接口時,它不會編譯。
using TestTypes = ::testing::Types<ImplementationOne, ImplementationTwo, ImplementationThree>
TYPED_TEST_SUITE(GenericDiffTester, DiffTypes);
顯然,問題在於fixture 要求test_class
是默認可構造的,這不適用於ImplementationThree
。
如何根據提供的類型 T 初始化類的模板化成員變量? 如果 T 的類型為 ImplementationOne 或 ImplementationTwo,我想默認構造 test_class。 否則,我想將其構造為帶有字符串的 ImplementationThree。
有沒有辦法直接用 Gtest 來做,而不需要一個 hacky 解決方案?
最簡單的方法是從您的非默認可構造類派生。 該派生類可以是默認可構造的:
class TestableImplementationThree : public ImplementationThree
{
public:
TestableImplementationThree() :
ImplementationThree("dummy")
{}
};
和:
using TestTypes = ::testing::Types<
ImplementationOne,
ImplementationTwo,
TestableImplementationThree>;
如果您想使用不同的構造函數參數來測試 ImplementationThree - 那么只需根據需要創建和測試盡可能多的可測試類。
如果您確實堅持要准確測試ImplementationThree
- 然后用某種持有者包裝所有類。 對於ImplementationThree
來說,專門化它的“持有者”來以不同的方式構建它。
template <typename T>
struct Holder
{
T tested_object;
};
template <>
struct Holder<ImplementationThree>
{
ImplementationThree tested_object{"dummy"};
};
template <typename T>
class GenericTester : public ::testing::Test,
protected Holder<T>
{
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.