While unit testing often requires testing internal (private) logic, what is the best fit for?

I believe that everyone is faced with a situation where there is a need to test the internal wiring of a class / object. I know that in compiled languages ​​this can be done by conditional compilation. Is this what I have to do for JavaScript? What's the usual way to accomplish such a task? Maybe I should just treat the class / object as a black box and check its results?

+1


source to share


1 answer


Testing the public contract object (i.e. the black box testing you mentioned) should be sufficient in most cases. Proper testing of public members should be done by most private / internal affairs. After all, why does the user of your class (be it another programmer, other objects / employees) care about what your objects are doing internally?

When you get to the point where you feel a strong need to test your internal affairs, see it as an opportunity to improve. Usually this need is the result of your code telling you something - "maybe I shouldn't be private", "maybe it should be reformed into a separate entity."



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

I sometimes realize that you just need to check the internals, but IMO, it's better to stop and think if you can make the code better (very often you will find out that you really can!). Treat internal testing as a last resort when all else fails.

+2


source







All Articles