Posted by: terryhowe | October 2, 2009

Clean Code: Unit Tests

The best chapter of Robert C. Martin’s Clean Code is the chapter on Unit Tests.  I think the ideas could be extended to automated functional tests as well.  Some of the interesting points include:

  • Given-When-Then:  A convention from RSpec for naming conventions.  Also known as the Build-Operate-Check in the Fitnesse world.  Every test should follow the given-when-then pattern.  The test data should be built, the operation should be called, and the result of the operation should be checked.
  • One Assert per Test:  In theory, every test should only have one assert, but sometimes it makes more sense to assert multiple things in a test rather than repeating a lot of “given-when” code.
  • Domain Specific Testing Language:  I think this concept is poorly named, but what it means is use naming conventions specific to testing and be consistent.  For example, start all your setup functions with the word given, your operation functions with the word when, and your check functions with the word then.
  • A Dual Standard: Test code should be as clean as production code, but it does not need to meet the same performance standard.
  • Single Concept per Test:  You can have multiple asserts in a test, but at least the test should only be testing one given-when-then scenario.
  • Fast:  Tests should be fast so that you run them frequently.
  • Independent:  Tests should be independent so that the order that the tests run is not important.
  • Repeatable:  Tests should be repeatable so that you can rely on the results and not dependent on an environment.
  • Self-Validating:  You shouldn’t need to read through log files to make sure they work properly.
  • Timely:  They should be written just before the production code is written.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: