Advertisements
Writing unit tests helps produce higher quality code on many levels.
- The availability of tests helps detect the introduction of bugs whenever the programmer adds new features or refactors the code. This is called regression testing.
- Tests also serve as a source of documentation about what code is really expected to do.
- The act of writing the tests challenges the programmer to consider possible edge cases and their consequences.
- Last but not least, the act of writing tests encourages the programmer to write code in small chunks that can be tested independently.
The last point is worth diving into. If we are writing code that needs to do three manipulations to an incoming string, the temptation is to write a function where the string comes in as an argument, the three manipulations are executed, and the resulting string is returned. When this function isn't working right it is hard to determine which of the three manipulations are failing. Your test case can only send a string in and compare the result with the expected result. How can you know which of the manipulations isn't working correctly? Breaking the function into smaller pieces, one for each manipulation, results in code that is easier to test. Test cases can then be written for each manipulation, better isolating the source of failure.
Unit tests can be often be scripted to run automatically, making them an ideal part of your development, build, and deployment process. You can run tests before committing new code to the repository. You can run the tests after adding new modules and thus ensure that previous functionality hasn't been compromised. You can run tests after deploying changes from a development environment to a staging environment thus cutting down on the dependency of trial and error to detect problems.