在使用Google测试时,我对继承方面感到困惑。我有一个class A
,其中包含protected
属性。如果我想要访问这些属性,我必须扩展该类,但同时我还需要扩展public ::testing::Test
,仅为了使用gtest
。
最优雅的解决方案是什么?
另外,我正在尝试避免使用#define protected public
。
在使用Google测试时,我对继承方面感到困惑。我有一个class A
,其中包含protected
属性。如果我想要访问这些属性,我必须扩展该类,但同时我还需要扩展public ::testing::Test
,仅为了使用gtest
。
最优雅的解决方案是什么?
另外,我正在尝试避免使用#define protected public
。
为了避免在被测试的类中留下测试痕迹,请使用带有夹具的多重继承:
class ToBeTested
{
protected:
bool SensitiveInternal(int p1, int p2); // Still needs testing
}
// Google-test:
class ToBeTestedFixture : public ToBeTested, public testing::Test
{
// Empty - bridge to protected members for unit-testing
}
TEST_F(ToBeTestedFixture, TestSensitive)
{
ASSERT_TRUE(SensitiveInternal(1, 1));
ASSERT_FALSE(SensitiveInternal(-1, -1));
}
class ToBeTested
{
public:
ToBeTested() = delete;
ToBeTested(int p): p1(p) {}
protected:
bool SensitiveInternal(int p2) {return p1 == p2;}// Still needs testing
const int p1;
};
// Stub to bridge the acess restrictions:
class ToBeTestedStub : public ToBeTested
{
public:
ToBeTestedStub(int p):ToBeTested(p) {}
FRIEND_TEST(ToBeTestedFixture, TestSensitive);
};
// Google-test:
class ToBeTestedFixture : public testing::Test
{
public:
void SetUp() override
{
stub = std::make_unique<ToBeTestedStub>(1);
}
// Using a pointer so we can instantiate the stub in the SetUp method.
std::unique_ptr<ToBeTestedStub> stub;
};
TEST_F(ToBeTestedFixture, TestSensitive)
{
ASSERT_TRUE(stub->SensitiveInternal(1));
ASSERT_FALSE(stub->SensitiveInternal(2));
}
这里展示了一个替代方案:这个答案。
// Stub to bridge the acess restrictions:
class ToBeTestedStub : public ToBeTested
{
public:
ToBeTestedStub(int p):ToBeTested(p) {}
using ToBeTested::SensitiveInternal;
};
class Base
{
public:
Base(int x);
virtual ~Base()=default;
protected:
bool myMethod();
}
class stubBase : public Base
{
public:
stubBase(int x) : Base(x){}
bool myMethod(){ Base::myMethod(); }
}
TEST(Base, myMethod)
{
stubBase stub(1);
EXPECT_TRUE(stub.myMethod());
}