DEV Community

Discussion on: Do you unit test private methods?

Collapse
 
rhymes profile image
rhymes

I don't test them anymore, I used to but I realized it's not needed.

Unit tests are supposed to test the unit of software that consists in the contract between you and the user of the functionality. The surface (be it a class, a function, a method, a package, or whatever) of the unit is whatever can be called from the outside.

That's the part that should be tested. Private methods are unknown by the outside world and the testing software is just another user of your unit.

In some languages you can't literally call private methods from the outside (which would make unit tests really tricky :D), Python doesn't really have them but we abide to the "underscore convention".

So no, you don't really need to test private methods. You can just call the public method that calls that private method and test if the expected output is there.

Collapse
 
phlash profile image
Phil Ashby

If you have code coverage measures in place, you can also eliminate dead code this way too - if those private methods never run with a full contract test in place - nuke 'em!