Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 编写可以访问private/protectedstate的单元测试_C++_Testing_Googletest_Boost Test_Gunit - Fatal编程技术网

C++ 编写可以访问private/protectedstate的单元测试

C++ 编写可以访问private/protectedstate的单元测试,c++,testing,googletest,boost-test,gunit,C++,Testing,Googletest,Boost Test,Gunit,我使用Boost测试进行单元测试。我通常有一个fixture结构: class ClassBeingTested { protected: int _x; // Want to access this directly in my unit tests }; struct TestFixture : public ClassBeingTested { // I can access ClassBeingTested::_x here but it mea

我使用Boost测试进行单元测试。我通常有一个fixture结构:

class ClassBeingTested
{
protected:
    int _x;             // Want to access this directly in my unit tests
};

struct TestFixture : public ClassBeingTested
{
    // I can access ClassBeingTested::_x here but it means i have to add getters for each test to call
    ClassBeingTested _bla;
};
但是,即使我的装置继承自
ClassBeingTested
或使用朋友关系,我也无法从每个单独的测试中访问私有/受保护的方法/状态:

BOOST_FIXTURE_TEST_CASE(test1, TestFixture)
{
    _bla.doSomething();
    BOOST_REQUIRE_EQUAL(_bla.x, 10);    // Compiler error. I cannot access ClassBeingTested::_x here
}
只有fixture,这意味着我必须为我希望进行的每个访问添加一个新的getter(或test)

有没有办法做到这一点?我必须将公共getter方法添加到
ClassBeingTested
中,这些方法仅由测试使用,这并不理想


(请不要回复“使用公共接口进行测试”,这并不总是可能的)。

您可以结交朋友测试好友,
struct ClassBeingTestedBuddy带有
朋友结构类正在测试的Buddy类中的code>

让TestBuddy类公开所有测试所需的所有受保护或私有变量或方法

看起来像

struct ClassBeingTestedBuddy {
    ClassBeingTested* obj;
    ClassBeingTestedBuddy(ClassBeingTested* obj_)
      : obj{obj_} {}
};
…再加上任何你想暴露的东西


这只是允许测试成为连接受保护和私有数据和方法的桥梁的一种方法。但是,由于它都是项目中的代码,对于您的测试使用,这是一种获得测试代码访问权限的合理方法,而无需对您的实际代码进行太多检测。

您可以结交一个朋友测试伙伴,
struct ClassBeingTestedBuddy带有
朋友结构类正在测试的Buddy并让test buddy类公开所有测试所需的所有受保护或私有变量或方法。它看起来像
struct ClassBeingTestedBuddy{ClassBeingTested*obj;ClassBeingTestedBuddy(ClassBeingTested*obj):obj{obj}加上任何你想公开的东西。@Eljay嘿,你能回答这个问题吗?