How to use unit tests effectively

by Adrian on September 4, 2009

To setup an effective unit testing process within a team implement the following processes:

Explain to the team why unit testing is important. Effective unit testing provides several important benefits, these include:

It is one of the key ways to promote quality within the development process. When used in collaboration with a strategy of regularly building a code base (such as continuous integration (CI) or a daily build) it provides a fast and efficient regression testing mechanism. This in turn encourages the process of refactoring, something which is an integral part of a maintaining a healthy codebase, that can respond quickly to changing business requirements.

If unit tests are written prior to actual code (a process known as test-driven development or TDD) they can provide a useful way for the to developer to focus on only writing the minimal amount of code that is required to implement a particular feature and not to be distracted by building functionality that may or may not be required at some point in the future. This is something that can dramatically improve productivity.

Establish an acceptable level of unit test code coverage and monitor it to ensure it is achieved. Ideally code coverage should be 100%, but this is not always possible or even desirable, a more realistic level is around 90%. One of the most efficient ways to monitor the level of code coverage is to integrate it into the build process. Tools like MSBuild or NAnt make it is possible for builds to fail if an acceptable level of code coverage is not attained.

Explain how to write good unit tests.

Good unit tests are:

Fast to execute. To ensure that they can be run frequently. This is particularly important in test-driven development where the so-called ‘red-green-refactor’ process requires regular changes to the same code.

Automated and repeatable. Unit tests should not dependent on any other tests having to be run first, this can make them hard to maintain.

Easy to run. It should be possible to run unit tests at the touch of a button.

Persistent. Once unit tests are written they should remain for future use.

Test only a single item of functionality, so if they fail it is easy to know what to fix.

Easy to implement. Most unit tests are written using a unit testing framework such as NUnit.

Well named to easily identify what has changed when a test fails. Well named tests also promote a way of documenting code to reduce the costly producing of maintaining additional documentation.

Previous post:

Next post: