Monday, September 12, 2005

Unit Testing Rules

A test is not a unit test if:

  • It talks to the database It communicates across the network
  • It touches the file system
  • It can't run at the same time as any of your other unit tests
  • You have to do special things to your environment (such as editing config files) to run it. 

Tests that do these things aren't bad. Often they are worth writing, and they can be written in a unit test harness. However, it is important to be able to separate them from true unit tests so that we can keep a set of tests that we can run fast whenever we make our changes.

I agree in that unit tests should be completely independent of their environment. I also agree in that you should rather use mock objects instead of e.g. a database. What I don't agree on is that it's supposed to be a bad thing to change your environment to be able to run a test. Let's say you run unit tests for a persistence component, why is it a bad thing to change the persistence implementation, so that mock objects are being used, before running the tests? If you are using  an automated tool, it can be done transparently, without any manual changes needed.

No comments: