How to write good Unit Tests? [closed]

An important point (that I didn’t realise in the beginning) is that Unit Testing is a testing technique that can be used by itself, without the need to apply the full Test Driven methodology.

For example, you have a legacy application that you want to improve by adding unit tests to problem areas, or you want to find bugs in an existing app. Now you write a unit test to expose the problem code and then fix it. These are semi test-driven, but can completely fit in with your current (non-TDD) development process.

Two books I’ve found useful are:

Test Driven Development in Microsoft .NET

A very hands on look at Test Driven development, following on from Kent Becks’ original TDD book.

Pragmatic Unit Testing with C# and nUnit

It comes straight to the point what unit testing is, and how to apply it.

In response to your points:

  1. A Unit test, in practical terms is a single method in a class that contains just enough code to test one aspect / behaviour of your application. Therefore you will often have many very simple unit tests, each testing a small part of your application code. In nUnit for example, you create a TestFixture class that contains any number of test methods. The key point is that the tests “test a unit” of your code, ie a smallest (sensible) unit as possible. You don’t test the underlying API’s you use, just the code you have written.

  2. There are frameworks that can take some of the grunt work out of creating test classes, however I don’t recommmend them. To create useful unit tests that actually provide a safety net for refactoring, there is no alternative but for a developer to put thought into what and how to test their code. If you start becoming dependent on generating unit tests, it is all too easy to see them as just another task that has to be done. If you find yourself in this situation you’re doing it completely wrong.

  3. There are no simple rules as to how many unit tests per class, per method etc. You need to look at your application code and make an educated assessment of where the complexity exists and write more tests for these areas. Most people start by testing public methods only because these in turn usually exercise the remainder of the private methods. However this is not always the case and sometimes it is necessary to test private methods.

In short, even experienced unit testers start by writing obvious unit tests, then look for more subtle tests that become clearer once they have written the obvious tests. They don’t expect to get every test up-front, but instead add them as they come to their mind.

Leave a Comment