DEV Community

Discussion on: Unit tests dos and don'ts

Collapse
 
farhanrosenborg profile image
farhan

Private methods are normally called from within a public method. So they will always be tested when you write tests for your public methods.

If that is not the case it means, the private method is not being used and should be removed from the class.

Collapse
 
dakujem profile image
Andrej Rypo

Yes, that's correct. I found myself however, that testing private and protected methods does make sense in certain cases.
Imagine a complex public method that abstracts part of its logic into private methods. Testing these, if there is an error, you will probably identify it easier if the error also shows in the tiny private method.
Furthermore, if you are building your class/app logic from bottom up using TDD (test driven dev), you will most probably encounter cases where you write tests for methods that you design as private.
Otherwise, I fully agree that if something is not used, it should be refactored.

Thread Thread
 
farhanrosenborg profile image
farhan

I am fine with testing private functions altough I never had any problems with just testing the public functions and I am doing that for past 4 years.

Your point which says "Imagine a complex public method that abstracts part of its logic into private methods."

I personally try to follow the Rules of Object Calisthenics (gist.github.com/bobuss/6534934), one of which says that Keep all classes less than 50 lines. With small classes it is really easy to see which scenerios need to be tested. If the tiny private method throws an Exception. It will also be thrown in the public function which is going to call that tiny private function, and from there it can be easily tested.

This is my personal opinion, I am just happy to see tests in any code :-)

Thread Thread
 
dakujem profile image
Andrej Rypo

I am just happy to see tests in any code
So so true! 😑