When To Test Private Methods
No, I’m not starting another flame war. Well… maybe a small one.
The stars must be aligning, otherwise I don’t have an idea why the same question came up so many times in my feed reader today. Or there’s something about great minds think alike after all.
Guy Kolbis asks “should we test private methods”. This is based on Chad Myers’ “Do not test private methods”. And Artem dissects the different cases where testing private methods might look like it makes sense.
I agree with all they are saying. Mostly there’s no good reason enough to test private methods. Except on one occasion. I find this example becoming a canonical one for me, since it happens a lot, but easy to ignore in favor of theoretical best practices discussion.
What if I just landed a big pile of code? No tests, not designed for testability. It has a complex algorithm buried inside. The public method that calls this private method does bunch of data stuff before and after. I’m not making this up, folks, it happens a lot, and specifically I faced the internal algorithm problem twice.
So you can’t refactor, because you might break something. You can use faking tools, like Isolator, to fake the dependencies, but in a lot of cases, mine for instance, it was filling a data set with a LOT of data. Writing tests for these would be painful to the level of where medication is needed. And all I want to test is that algorithm.
Know what I did then? Don’t tell anyone – I made the method public just so I can test it. But that’s beside the point. I could invoke the private method using reflection to achieve the same effect. I needed to test part of the code without moving the other parts. And that’s what I did.
So when should you test private methods? When you don’t have a choice. And accept the consequences.