Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News Guidelines for Better Unit Tests

Guidelines for Better Unit Tests

Leia em Português

Jimmy Bogard, wrote an article: “Getting value out of your unit tests”, where he gives three rules:

  1. Test names should describe the what and the why, from the user’s perspective” – the idea is that a developer should be able to read the name and understand what the intended behavior is.
  2. Tests are code too, give them some love” – production code isn't the only place that you should do your refactoring. Readable tests are easier to maintain and easier for next person to understand. “I hate, hate long, complex tests.  If a test has 30 lines of setup, please put that behind a creation method.  A long test just irritates and leaves the developer cross-eyed.  If I don’t have long methods in production code, why would I allow this in our test code?”
  3. Don’t settle on one fixture pattern/organizational style” – Sometimes the standard pattern of one class, one test fixture doesn’t work.

Lior Friedman added: “Rule #0 - Test external behavior and not internal structure.” Or, test the expectations for a class not its current structure.

Ravichandran Jv added his own rules:

    1. One Assert per test (where possible). 
    2. If there are any "if else" inside a test, move the branches to individual test methods. 
    3. Methods under test, if they, too, have if else branches, the method should be refactored.
    4. Name of the method should be the kind of test. For instance, TestMakeReservation is different from TestMakeNoReservation().

Charlie Poole, author of NUnit, rewords one Assert per to test to one “Logical Assert” – saying “Sometimes, due to a lack of expressiveness in the testing api, you need to write multiple physical asserts to achieve the desired result. Much of the development in the NUnit framework api has been out of an attempt to get a single assert to do more work.”

Bryan Cook produces a considerable list of his own:

  1. DO: Name Fixtures consistently
  2. DO: Mimic namespaces of Target Code
  3. DO: Name Setup/TearDown methods consistently
  4. CONSIDER: Separating your Tests from your Production Code
  5. DO: Name Tests after Functionality
  6. CONSIDER: Use "Cannot" Prefix for Expected Exceptions

Bryan has over a dozen more suggestions.

Finally a couple of people suggested Gerard Meszaros’s book: “xUnit Test Patterns: Refactoring Test Code

Previously on InfoQ: Recommended TDD Tutorials, Designing for Testability, Unit Testing Tips from Googleand Making TDD Stick: Problems and Solutions for Adopters

Rate this Article