While unit testing I frequently require to test in

2019-07-29 21:39发布

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?

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-29 22:03

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".

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.

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.

查看更多
登录 后发表回答