When to write a unit test?

In my opinion the following are situations to implement another unit test.
  • Before writing new production code (TDD)
  • Before fixing a bug (exposing the bug with the test)
  • In order to get to know an API where the documenation doesn't help much
  • When encountering untested yet critical code (e.g. using a coverage tool)
  • In case you are bored and have nothing else to do ;-)
Of course, when strictly following TDD, the fourth situation cannot occur. However in real life we have to cope with untested legacy code.