I am new to unit testing but am beginning to think I need it. I have an ASP.NET web forms application that is being extended in unforeseen directions meaning that certain bits of code are being adapted for multiple uses. I need to try and ensure that when changing these units I don't break their original intended use. So how do I best go about applying unit tests retrospectively to existing code? Practical advice appreciated. Thanks
One of the unspoken benefits of Unit testing is the way it pushes class designs toward lower coupling. If you try to add UnitTesting in at the end, you should be prepared for either:
- cases that you can't test a Unit due to coupling
- redesigning classes to remove coupling, which of course is not very safe to do without existing Unit tests.
In particular, a couple of things to watch out for are:
- classes that new-up other classes (usually high coupling here).
- classes that rely on infrastructure that is non-existent at the time of Unit Testing, such as HttpRequest and databases
EDIT
Wikipedia explains Unit Testing:
The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. A unit test provides a strict, written contract that the piece of code must satisfy.
This is about testing a method. This is not about testing a method plus a database. You can do automated tests that test a method plus a database, but those aren't unit tests.
Very slowly!
I'm currently doing the same thing on my project and it is a lot of effort. In order to unit test existing classes they often need to be completely redesigned...and because of high coupling changing a single class can result in changes that need to be made in several dozen other classes.
The end result is good clean code that works, can be extended, and can be verified....but it does take a lot of time and effort.
I've bought myself several books on unit testing that are helping me through the process.
You might want to consider getting yourself xUnit Test Patterns and Working Effectively with Legacy Code.
Don't change a line of code until you've written tests for the method it's in. The biggest mistake I see people making is they redesign the class to make it more testable before they write the tests for it. This is counter-productive, because you will break something.
The right way to go is to write a complete set of tests for a class (or method, the level of granularity is up to you) before you change it. These tests are your safety net that allow you to confidently make changes. If you find that you can't write tests for a class, maybe because it's too heavily coupled to another class, then your first set of tests should be for the two classes together, then your next step should be to decouple the classes.
Having literally just done this I'd like to suggest you add your unit tests one at a time and fix them at the same pace.