【发布时间】:2020-04-27 23:39:41
【问题描述】:
我使用 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 或使用朋友关系,我也无法从每个单独的测试中访问私有/受保护的方法/状态:
BOOST_FIXTURE_TEST_CASE(test1, TestFixture)
{
_bla.doSomething();
BOOST_REQUIRE_EQUAL(_bla.x, 10); // Compiler error. I cannot access ClassBeingTested::_x here
}
只有fixture,这意味着我必须为我希望进行的每次访问添加一个新的getter(或测试)。
有什么方法可以实现吗?我必须向 ClassBeingTested 添加公共 getter 方法,这些方法仅供测试使用,这并不理想。
(请不要回复“使用公共接口进行测试”,这并不总是可能的)。
【问题讨论】:
-
您可以在类中结交朋友测试伙伴
struct ClassBeingTestedBuddy;和friend struct ClassBeingTestedBuddy;,并让测试伙伴类公开所有测试所需的所有受保护或私有变量或方法。它看起来像struct ClassBeingTestedBuddy { ClassBeingTested* obj; ClassBeingTestedBuddy(ClassBeingTested* obj_) : obj{obj_} {} };加上您想要公开的任何内容。 -
@Eljay 嘿,你能把这个作为答案吗?
标签: c++ testing googletest boost-test gunit