c++ - 编写可以访问私有(private)/ protected 状态的单元测试

标签 c++ testing googletest boost-test gunit

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

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或使用 friend 关系我无法从每个单独的测试中访问私有(private)/ protected 方法/状态:
BOOST_FIXTURE_TEST_CASE(test1, TestFixture)
{
    _bla.doSomething();
    BOOST_REQUIRE_EQUAL(_bla.x, 10);    // Compiler error. I cannot access ClassBeingTested::_x here
}

只有fixture,这意味着我必须为我希望进行的每次访问添加一个新的getter(或测试)。

有什么办法可以做到这一点?我必须将公共(public) getter 方法添加到 ClassBeingTested仅由测试使用,这并不理想。

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

最佳答案

可以交个 friend 测试好友,struct ClassBeingTestedBuddy;friend struct ClassBeingTestedBuddy;class ClassBeingTested .

让测试伙伴类公开所有测试所需的所有 protected 或私有(private)变量或方法。

它看起来像...

struct ClassBeingTestedBuddy {
    ClassBeingTested* obj;
    ClassBeingTestedBuddy(ClassBeingTested* obj_)
      : obj{obj_} {}
};

...加上您想公开的任何其他内容。

这只是让测试成为连接 protected 和私有(private)数据和方法的桥梁的一种方式。但是由于它是您项目中的所有代码,因此对于您的测试使用,这是一种无需过多检测实际代码即可访问测试代码的合理方法。

关于c++ - 编写可以访问私有(private)/ protected 状态的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61470300/

相关文章:

reactjs - 测试 React Select 组件

ruby-on-rails-3 - 轨道测试 : session mechanism creates new cart instead of using fixture

c++ - Googletest - DeathTest 无法捕获来自 Qt 应用程序的断言,例如 Q_ASSERT 等。

c++ - gmock : Returns distinct values on each mock invocation

c++ - 重载函数不明确

c++ - 检查正确的输入会导致无限循环

C++ 小错误 : "... is not a static data member of ‘class ...' "

testing - 是否可以使用无服务器框架将测试事件推送到 AWS Lambda?

c++ - "dynamic_cast"之后的 NULL 指针实际上可以取消引用吗?

c++ - 输入 int 和 str 并将它们存储到两个单独的列表中