BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Testing
.NET 1.1+

Unit Testing

This is the first in a series of articles describing the use of automated unit testing techniques. Unit testing allows verification of the functionality of a program. Automated unit testing validates software automatically by executing test code.

Tests Take Too Long to Run

Some programmers complain that automated tests take too long to execute, slowing the development process. There are usually two reasons for this misconception. The first is that the tests being created may not be true unit tests. For example, consider a method that is responsible for changing data in a database. Tests for such a method may involve resetting a database to a known state, executing the method and then reading the data from the database to ensure that it is as expected. When you have many such tests, the overall time required to execute them will grow quickly. However, these are integration tests, not unit tests. A true unit test would isolate the method from the database entirely.

The second reason that tests take a long time to run is that some processes are slow. You may be testing an algorithm that takes several seconds to execute or you may be including some integration tests in your test suite. Both situations are valid. To alleviate the problem, most testing frameworks allow you to categorise your tests and be selective in which categories are executed. You can use these features to separate long-running tests and execute these less often.

Throwaway Code Does Not Require Testing

Some software is written to be used once only and then discarded. If the software performs a very basic task it may be sensible to develop it without automated unit tests. If the process is complicated, particularly if it may damage important data if it is incorrect, you should probably include automated testing. You should also consider the common situation that the single-use code is seen as useful for other projects.

Unit Tests Damage Your Design

A concern amongst some programmers is that automated unit testing can adversely affect the design of your software. One of the key arguments is that in order to test methods that should be private you will make them public so that a test framework can access them. This is a valid concern as private methods are implementation details that should not be visible outside of their containing classes. Making them public risks that they will be used externally, breaking encapsulation rules and making it more difficult, if not impossible, to refactor a class. To avoid this problem we must remember that we are testing the behaviour of the code, not the implementation details. This behaviour is almost always indirectly testable via the public interface of a class.

9 March 2011