[英]Writing unit tests which may access private/protectedstate
I use Boost Test for unit tests.我使用 Boost Test 进行单元测试。 I typically have a fixture struct:
我通常有一个夹具结构:
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;
};
However, even if my fixture inherits from ClassBeingTested
or uses a friend relationship I cannot access private/protected methods/state from each individual test:但是,即使我的夹具继承自
ClassBeingTested
或使用朋友关系,我也无法从每个单独的测试中访问私有/受保护的方法/状态:
BOOST_FIXTURE_TEST_CASE(test1, TestFixture)
{
_bla.doSomething();
BOOST_REQUIRE_EQUAL(_bla.x, 10); // Compiler error. I cannot access ClassBeingTested::_x here
}
only the fixture, which means I have to add a new getter (or test) for each access I wish to make.只有fixture,这意味着我必须为我希望进行的每次访问添加一个新的getter(或测试)。
Is there any way to achieve this?有什么办法可以做到这一点? I have to add public getter methods to
ClassBeingTested
which are only used by tests, which isn't ideal.我必须向
ClassBeingTested
添加公共 getter 方法,这些方法仅供测试使用,这并不理想。
(Please no replies of 'test using the public interface', that's not always possible). (请不要回复“使用公共接口进行测试”,这并不总是可能的)。
You can make a friend test buddy, struct ClassBeingTestedBuddy;
可以交朋友测试好友,
struct ClassBeingTestedBuddy;
with friend struct ClassBeingTestedBuddy;
与
friend struct ClassBeingTestedBuddy;
in the class ClassBeingTested
.在
class ClassBeingTested
。
Have the test buddy class expose all the protected or private variables or methods that you need for all your tests.让测试伙伴 class 公开所有测试所需的所有受保护或私有变量或方法。
It'd look like...它看起来像...
struct ClassBeingTestedBuddy {
ClassBeingTested* obj;
ClassBeingTestedBuddy(ClassBeingTested* obj_)
: obj{obj_} {}
};
...plus anything else you'd want to expose. ...加上你想暴露的任何其他东西。
This is but one way of allowing the tests a bridge to the protected and private data and methods.这只是让测试成为连接受保护和私有数据和方法的桥梁的一种方式。 But since it is all code in your project, for your testing use, it is a reasonable way of getting the test code access without too much instrumenting your actual code.
但是由于它是您项目中的所有代码,因此对于您的测试使用,这是一种合理的方式来获取测试代码访问权限,而无需过多地检测您的实际代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.