I’ve been working on a project and recently had time to clean up the source code a little.
When you don’t have complete specifications for a project, the source code tends to get messy. You add some new code, thinking you’ll only call it once. Then, a month later, there’s a request to add a similar feature somewhere else. So, you do a quick copy paste. Another month passes and you get a similar request for a different area of the program.
If you care about code quality, you create a shared function used in all three places (assuming they really are doing the same thing). That ensures that the same logic is used throughout your program, and every place it’s used can handle all the edge case scenarios that may happen.
But what about your unit tests?
Something I often see (and, sometimes do myself) is to copy a similar unit test, make the specific changes for the new test, and go back to the “real” programming. This is especially true when you’re under pressure to meet a deadline.
However, this leads to your test classes become fragile.
After a while, you’ll have the same problems you do with not cleaning up your application’s source code. Some tests won’t handle all the situations they may encounter (giving you a false positive or negative for the test). If you ever change the program, you may find that you now need to make the same change in a dozen unit tests. In addition, it’s easier for the other programmers (or your future self who’ll be modifying the app in nine months) to understand what the tests are supposed to be covering.
So, in the project where I’ve been cleaning up the source code, I also started to clean up the test classes.
The first test class I worked on, I’ve been able to reduce the number of lines from 1600+ to 480. It’s so much easier to read now. I also found one test that wasn’t testing something it should have been testing. Now I can feel better that the tests are covering more situations that may happen when the program is in use.
If you get a little free time, look at your unit test classes. See if you can improve the quality, and clarity, of the code in them.
It will make your life easier when you come back in the future to modify your program.