Rules for good unit tests

  • Test method names should be sentences (This_method_does_this(){})
  •  Test the happy path – the most common/important functionality (acceptance criteria should be executable)
  • Test at the highest level that is practical
  • Unit Tests should not:
  • Talk to the database
  • Talk to the network
  • Touch the file system
  • Don’t change business logic to write the code
  • Depend on any other tests (can be run at any time, in any order)
  • Depend on environment variables (USE MOCKS!)
  • Tests should be fast (lengthy tests are doing something wrong)
  • Less than 10 lines of code
  • Only one or two logical asserts per test
  • Don’t write tests after development is done 

Further reading:


2 thoughts on “Rules for good unit tests”

  1. Only one or two asserts per test? How the heck do you write tests with only two assertions?
    Consider something simple like setting the FirstName property on a Person object. Right off the bat I’ve got three assertions:

    1. Did the property actually get set?
    2. Was the calculated property FullName updated accordingly?
    3. Was the HasChanges flag set to true?

    I program in XAML, so I also need:

    4. Was the property change notification raised for “FirstName”?
    5. Was the property change notification raised for “FullName”?
    6. Was the property change notification raised for “HasChanges”?

    Since assertions four thru six depend on prior state, I also need to verify the state of the object prior to actually running the test. Otherwise the error message will be misleading.

    7. Is the FirstName property different than what I am setting it to?
    8. Is the LastName property (and any other value that feeds into FullName) what I am expecting?
    9. Is the HasChanges flag false?

    If I was really being diligent, I would include assertions to make sure no other property was changed by accident. Fortunately, a bit of reflection code in a helper method can handle that.

    10. Was any other property changed unintentionally? [two lines of code, one to capture and one to compare]

    How am I supposed to write a test that is only 10 lines long when I need 11 lines of code just for the assertions?

Leave a Reply