问题描述
我在测试夹具中有一个受保护的静态方法,我希望从辅助函数而不是从单元测试函数本身调用。
class Fixture
{
...
protected:
static void fixture_func( int foo );
};
void helper_func( int bar ) {
Fixture::fixture_func( bar );
}
TEST_F( Fixture,example_test ) {
fixture_func( 0 ); //Line 1: This is how you would normally call the method
helper_func( 0 ); //Line 2: This is how I need to call the method
}
当我尝试第2行时,很明显会收到一个错误消息,指出该方法“不可访问”,因为它是fixture
中受保护的方法。我该如何以某种方式将测试夹具传递给helper_func
,或者将fixture_func
置于helper_func
的范围内?
如果您想知道,仅从单元测试本身调用fixture func
是不可行的,因为我正在设计一个测试框架,旨在简化用于特定目的的fix_func的使用。我也无法对fixture
进行重要更改。
解决方法
您不能从类外部调用 protected
或private
方法,无论该方法是static
还是调用函数是C-样式一。
在任何情况下,您都需要在Fixture::
之前使用类范围fixture_func
:
void helper_func( int bar ) {
Fixture::fixture_func( bar );
}
您需要以某种方式使fixture_func
成为public
,您可以尝试:
class FixtureExpanded : public Fixture { };
void helper_func( int bar ) {
FixtureExpanded::fixture_func( bar );
}