Поделиться через


Writing Unit Tests to Describe the Programmer's Intent

Brian Button has a great post with an example on how to write descriptive unit test fixtures and unit tests.  I would add that there are four things that define a descriptive, well written unit test:

  • Descriptive. A descriptive name for the test is key.  Well written developer/unit tests do not need comment header blocks (unless you are generating docs from them for a specific reason).  The name should describe, explicitly, exactly what is being tested.  I know that, in the past, I have been heckled by fellow team members that thought my method names were way too long.  They may have been a bit long, but anyone who read the code could tell what was going on without comments or documentation.
  • Organized. The test is organized with the three A's:  Arrange, Act, Assert. Basically, in as simple a manner possible, setup what is needed for the test (Arrange), call the method under test (Act), and then have your asserts to verify that everything behaved as intended (Assert).  (Note: I am borrowing this concept from others, including the person I heard it from (Peter Provost), but off the top of my head I cannot remember the originator of this organization scheme).
  • Simple.  Developer tests (unit tests) should be as simple as possible.  If I have a test that is more than about 10 lines of code, I examine very carefully to ensure that it is not really three or four tests merged together.  Sometimes, complicated setup cannot be avoided, but try to keep it simple.
  • Self-contained.  When I read a unit test, I should not need to look in 5 different setup methods to figure out what is going on.  A well written unit test is a single block of code that describes the developer's intent clearly.  While there is often the need for an object factory or helper methods (usually for the Arrange part of the test), these should be well named so no one needs to read the code to understand what they do. 

Of course, not every unit test can be a perfectly written unit test, but these ideas should be kept in mind as you write your code.  And after reviewing the list again, all four of these ideas should be applied to any and all code, not just unit test code.