April 7, 2009

Thoughts On Unit Tests

A few things I’d tell someone learning about unit testing:

  • A unit test should focus on one small, very specific piece of functionality.
  • Unit tests serve as documentation.  You should be able to review a piece of code’s unit tests in order to learn its behavior.
  • It’s okay to repeat some code in unit tests if it helps clarify the tests and make them more expressive.
  • Unit test names should be descriptive and clearly convey what the test is trying to verify.
  • Unit tests should be very fast.  Ideally, each one runs in 0.1 seconds or faster.
  • Unit tests should be repeatable.  Remove all environmental dependencies and any other factors that might lead to inconsistent test results.
  • If you find it hard to write a unit test (such as it’s too hard to break a dependency or you have to interact with a database), then there’s something wrong with your code.  Refactor your code in order to make it easier to test.
  • Don’t worry about 100% test coverage.  Strive for high coverage, but don’t worry about testing every minor, trivial case. 

0 comments:

Post a Comment