使用googletest测试受保护的成员

The*_*red 5 c++ testing inheritance protected googletest

googletesting时我对继承感到困惑.我有一个class Aprotected属性.如果我想访问那些我必须扩展该类,但同时我还需要扩展public ::testing::Test为唯一的目的gtest.

这个问题最优雅的解决方案是什么?我也试图避免#define protected public

小智 13

为避免在测试类中留下测试痕迹,请使用夹具的多重继承:

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));
}
Run Code Online (Sandbox Code Playgroud)


lis*_*isu 5

有一个 FRIEND_TEST 声明,用于被测试类的标头中。基本上,它将测试定义为班级的朋友。在我的用例中,我们在 RELEASE 模式下编译时禁用所有测试包含,因此它不会对真正的可执行文件造成任何损害。

看看这个