我使用 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/