• Linas Naginionis
Software Craftsmanship

You should never test non public methods

You should never test non public methods

One of biggest misconceptions I see when someone is doing TDD, is the willingness to test all the methods (even private and protected) in the System Under Test. It may appear to be a good thing to do at first (more tests), unless you try to think about consequences that may arise because of this behavior.

First of all, the concept of testing the methods itself is fundamentally wrong. What you need to test is the behavior of a System Under Test. Your system works correctly not when all of it’s methods are called, but when it behaves correctly.

One of the main flaws of non public method testing is the short-living of these tests. It’s impossible to write perfect code at the first time, we know that we’ll need to refactor our code a lot. And constant refactoring is a good thing because we can start from simpler things and improve our system over time. But what happens when our refactoring is done? Most of these unit tests are broken now, because we’ve changed the internal stuff. And what is this internal stuff? It is the implementation details and they are what is mostly changing over time… Let’s say we have our Repository interface. One day it will use Oracle implementation, another day – MongoDB and so on.

Another thing to note is that it is enough to test only public APIs because all the private and protected stuff will be tested implicitly by them. Of course it means that we need to write detailed unit tests covering all possible behaviors. But that’s what TDD and unit testing is all about.

Leave a Reply

Your email address will not be published. Required fields are marked *