虽然单元测试我经常需要测试内部(私有)逻辑,但最佳实践是什么? [英] While unit testing I frequently require to test internal (private) logic, what is the best practice for this?

查看:44
本文介绍了虽然单元测试我经常需要测试内部(私有)逻辑,但最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信每个人都遇到过需要测试类/对象内部接线的情况.我知道在编译语言中,这可以通过条件编译来完成.这也是我应该为 JavaScript 做的吗?完成此类任务的常用方法是什么?也许我应该将类/对象视为黑盒并仅测试其结果?

I believe everyone encounters a case when there's necessity to test internal wiring of the class/object. I know that in compiled languages this could be done through conditional compiling. Is this what I should do for JavaScript as well? What's the usual way to accomplish such task? Maybe I should just treat the class/object as a Black Box and only test it's outcomes?

推荐答案

测试对象的公共契约(即你提到的黑盒测试)大部分时间应该足够了.公共成员的适当测试覆盖率也应该行使大多数私有/内部成员.毕竟,为什么你的类的用户(无论是其他程序员、其他对象/合作者)关心你的对象在里面做什么?

Testing object's public contract (ie. black box testing you mentioned) most of the times should be enough. Proper test coverage of public members should exercise majority of private/internals as well. After all, why would user of your class (be it other programmer, other objects/collaborators) care about what your objects do inside?

当您感到强烈需要测试内部结构时,请将其视为改进的机会.通常,这种需求是您的代码沟通的结果你的东西 - 也许我不应该是私密的"也许值得将我重构为独立的存在".

When you arrive at the point that you feel a strong need of testing internals, treat it as an opportunity to improve. Usually, such need is a result of your code communicating you something - "maybe I shouldn't be private", "maybe it's worth to refactor me into separate being".

另外,请记住,内部测试会使您的测试更加脆弱.虽然您的对象/类功能(合同)可能保持不变,但实现可能会经常改变.考虑用 3rd 方/外部库替换您自己的代码段(很常见的更改)-这是破坏测试的原因吗?不是.

Also, keep in mind that testing internals makes your tests more fragile. While your object/class functionality (contract) might remain the same, implementation might change fairly often. Think about replacing your own pieces of code with 3rd party/external libraries (quite common change) - is this a reason to break your tests? It is not.

我意识到有时您只需要测试内部结构 - 但是 IMO,最好停下来思考您是否可以使您的代码更好(通常您会发现您确实可以!).当其他一切都失败时,将内部测试作为最后的手段.

I realize sometimes you just have to test internals - but IMO, it's better to stop then and think whether you can make your code better (very often you'll find out you indeed can!). Treat testing internals as a last resort when everything else failed.

这篇关于虽然单元测试我经常需要测试内部(私有)逻辑,但最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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