我想使用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测试:高级指南.
有没有其他方法来测试私有方法?每种选择有哪些优缺点?