Unit-testing – Unit testing method that calls multiple private methods

testingunit testing

I've been reading a lot about unit testing recently and there seems to be a debate online about whether private methods should be tested or not.

If I have an interface that exposes one method, but that method is quite complex and calls multiple other private methods and also makes use of other objects, how do I go about testing that method? Surely I should be testing the smallest units possible, even though many of these will be private methods belonging to the class under test?

Is testing a method that is made up of multiple smaller methods really an integration test?

Best Answer

No, it's not an integration test. A unit test tests one unit of executable code, and in procedural languages that usually equates to a method.

The test must make sure that this unit of code does its own task correctly, and nothing else. If our method calls multiple private methods, then you must test the effect of all those private bits of code. For instance, if it constructs a complex object with many different attributes, then you must test the value of all those attributes. If it does different things in different circumstances, then you must exercise all those different circumstances - probably in multiple tests. There is no reason for writing only one test for one method; if the circumstances are different enough, then it's almost always clearer to write multiple tests with different fixtures than to cram it all into one test.

Of course, if your method really is too complicated, there may be a very good case for refactoring it into multiple smaller methods. But that is true completely independent of testing; the fact that one method should do exactly one thing is a good principle to follow to begin with. The main reason for refactoring is that it makes the business code easier to understand and extend. The fact that it makes testing easier is just a collateral benefit.

Related Topic