小编Car*_*pez的帖子

使用GoogleTest测试私有方法的最佳方法是什么?

我想使用GoogleTest测试一些私有方法.

class Foo
{
private:
    int bar(...)
}
Run Code Online (Sandbox Code Playgroud)

GoogleTest允许使用两种方法.

选项1

使用FRIEND_TEST:

class Foo
{
private:
    FRIEND_TEST(Foo, barReturnsZero);
    int bar(...);
}

TEST(Foo, barReturnsZero)
{
    Foo foo;
    EXPECT_EQ(foo.bar(...), 0);
}
Run Code Online (Sandbox Code Playgroud)

这意味着在生产源文件中包含"gtest/gtest.h".

方案2

测试夹具声明为类的朋友并在夹具中定义访问器:

class Foo
{
    friend class FooTest;
private:
    int bar(...);
}

class FooTest : public ::testing::Test
{
protected:
    int bar(...) { foo.bar(...); }
private:
    Foo foo;
}

TEST_F(FooTest, barReturnsZero)
{
    EXPECT_EQ(bar(...), 0);
}
Run Code Online (Sandbox Code Playgroud)

方案3

PIMPL方法.

有关详细信息:Google测试:高级指南.

有没有其他方法来测试私有方法?每种选择有哪些优缺点?

c++ unit-testing private googletest

33
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×1

googletest ×1

private ×1

unit-testing ×1