Wednesday, September 29, 2010
These are some qualities of a good unit test: fast, small, focused (atomic), and isolated (order-independent).

A good unit test will execute in MILLISECONDS. NOT seconds. If a test takes more than a few hundred milliseconds to execute, it is probably too slow. This is not just an arbitrary performance metric...

Let me explain the philosophy behind this tenet.

A unit test suite should contain dozens if not hundreds of tests, organized into classes that have specific testing focuses. If a test runs in 1 SECOND (1000 ms) and there are 100 of these, that is almost a 2-minute wait for a developer to wait for the results of the suite. And we do this over and over and over... If we have to wait more than a few seconds (7 seconds is about the maximum time to keep the attention of the average developer) then the mind wanders, we get distracted, and it interrupts our workflow.

Not to mention the lost time... unit tests as a suite are (or SHOULD be) run frequently. Just imagine multiplying 2 minutes x 15 times per day (conservatively) x number of developers x developer rate per hour... This turns out to be quite an expense. Not to mention that the expense grows over time as new tests are added.

Tips:
- any unit tests that need to hit a database are not unit tests...
- any tests that need a network connection are not unit tests...
- some even say any tests that need a disk FILE are not unit tests...

Any of these issues can be resolved by the use of dependency injection and substituting mock objects in place of the database, service, or network resource. Using these objects will decouple the code from the service, and allow it to execute in isolation without requiring the actual resource. And, it will be FAST.

It's really worth doing, when we look at all the benefits. Take your unit tests to the next level and remove the integration with external resources. Make the tests fast, and everyone benefits.

Mocks | TDD | Unit Tests
Wednesday, September 29, 2010 8:50:21 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]  |  Trackback
© Copyright 2012, John E. Boal