Skip to content Skip to sidebar Skip to footer

While Unit Testing I Frequently Require To Test Internal (private) Logic, What Is The Best Practice For This?

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 co

Solution 1:

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.

Post a Comment for "While Unit Testing I Frequently Require To Test Internal (private) Logic, What Is The Best Practice For This?"