I am now doing unit testing on an application which was written over the year, before I started to do unit-testing diligently. I realized that the classes I wrote are hard to unit test, for the following reasons:
- Relies on loading data from database. Which means I have to setup a row in the table just to run the unit test (and I am not testing database capabilities).
- Requires a lot of other external classes just to get the class I am testing to its initial state.
On the whole, there doesn’t seem to be anything wrong with the design except that it is too tightly coupled (which by itself is a bad thing). I figure that if I have written automated test cases with each of the class, hence ensuring that I don’t heap extra dependencies or coupling for the class to work, the class might be better designed.
Does this reason holds water? What are your experiences?
Yes you are right. A class which is
not unit testablehard to unit test is (almost always) not well designed (there are exceptions, as always, but these are rare – IMHO one should better not try to explain the problem away this way). Lack of unit tests means that it is harder to maintain – you have no way of knowing whether you have broken existing functionality whenever you modify anything in it.Moreover, if it is (co)dependent with the rest of the program, any changes in it may break things even in seemingly unrelated, far away parts of the code.
TDD is not simply a way to test your code – it is also a different way of design. Effectively using – and thinking about using – your own classes and interfaces from the very first moment may result in a very different design than the traditional way of “code and pray”. One concrete result is that typically most of your critical code is insulated from the boundaries of your system, i.e. there are wrappers/adapters in place to hide e.g. the concrete DB from the rest of the system, and the “interesting” (i.e. testable) code is not within these wrappers – these are as simple as possible – but in the rest of the system.
Now, if you have a bunch of code without unit tests and want to cover it, you have a challenge. Mocking frameworks may help a lot, but still it is a pain in the ass to write unit tests for such a code. A good source of techniques to deal with such issues (commonly known as legacy code) is Working Effectively with Legacy Code, by Michael Feathers.