在C ++中使用friend类和添加访问器进行单元测试? [英] Using a friend class vs. adding accessors for unit testing in C++?

查看:255
本文介绍了在C ++中使用friend类和添加访问器进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好添加返回单元测试的对象的内部状态的函数,而不是使测试类成为朋友?

Is it better to add functions that return the internal state of an object for unit testing, as opposed to making the testing class a friend? - especially, when there is no use for the functions except for the case of unit testing.

推荐答案

单元测试需要95%的单元测试时间只测试一个类的公开暴露的表面。如果你测试下面的东西,这是测试实现细节,这本质上是脆弱的,因为你应该能够轻松地改变实现,并仍然有测试工作。不仅是脆弱的,而且你也可以试着测试在计划的使用情况下不可能的事情,这是浪费时间。

Unit tests should 95% of the time only test the publicly exposed surface of a class. If you're testing something under the covers, that's testing implementation details, which is inherently fragile, because you should be able to easily change implementation and still have the tests work. Not only is it fragile, but you could also be tempted into testing things that aren't actually possible in planned usage scenarios, which is a waste of time.

如果要添加的访问器的点只是为了测试函数是否有所需的效果,你的类设计可能违反另一个原则,这是一个状态机类应该总是清楚它的状态,如果影响当人们与课堂互动时会发生什么。在这种情况下,提供这些只读存取器是正确的。如果它不影响类的行为,请参阅我以前的一点关于实现细节。

If the point of the accessors you want to add is just to test whether the function had the desired effect, your class design may violate another principle, which is that a state-machine-like class should always make it clear what state its in, if that affects what happens when people interact with the class. In that case, it'd be right to provide those read-only accessors. If it doesn't affect the class's behavior, refer back to my previous bit about implementation details.

正如你正确地说,混乱一个类的公共表面未使用的材料由于其自身的原因也是不期望的。

And as you rightly said, cluttering up the public surface of a class with unused stuff is also undesirable for its own reasons.

如果我在您的情况下选择访问者和朋友之间,我会选择亲友,因为拥有你的测试,并可以改变它在一个捏。你可能不拥有的小丑谁找到一个方法使用你的额外的访问者,然后你会被卡住。

If I had to pick between accessors and friending in your case, I would choose friending, simply because you own your test and can change it in a pinch. You may not own the code by the clown who finds a way to use your extra accessors, and then you'll be stuck.

这篇关于在C ++中使用friend类和添加访问器进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆