Should we make private methods public to test them?

I saw this interesting tweet recently about testing private methods…

So should we make private methods public to test them?

IMHO this is the wrong approach, not because it breaks encapsulation BUT…. because the method was likely made private for a reason.. almost certainly because it’s an implementation detail.

And…. what’s the issue with testing implementation details directly? Well when you test the specifics of how a particular behaviour or use case is implemented rather than just the what (eg. expected outputs) you reduce your ability to refactor without having to change your tests.

When you change a test… the value it provided you in terms of guarding against regression bugs is severely reduced…why?…. well because at this point you may have a passing green test BUT you don’t know if that is a genuine pass or if you’ve done something stupid during the rewrite of the test. For some reason developers seem to think they are better coders when writing unit tests.

Keep tests high level and focused on behaviour

The ideal scenario is where you can refactor as much code as possible without having to touch your tests.. to support this tests should be kept high level and focused on behaviour.

I’ve shared this talk a few times but if you find you can’t refactor without having to always change tests or that your tests are actually acting as a barrier to change rather than facilitating it please check out Ian Coopers excellent talk… “TDD, Where Did It All Go Wrong

Links

Lots of great discussion on my LinkedIn profile where I first shared this tweet and my response…