Monday, July 23, 2007

Seven Metrics to Improve Your Unit Testing

Unit testing is tough, regardless of manual or automated, test-first or test-after. With any of the approaches, there are certain metrics to pay attention to while you code. Staying within acceptable levels means your code will be much more testable, whether you unit test or not!

  • Parameters - Each parameter added to a method's signature increases the number of possible ways that method can be invoked, eventually creating an unmanageable combinatorial problem. By limiting the number of parameters to three or fewer, you can easily increase the testability of your code.
  • Exceptions - Each thrown exception represents a distinct error condition that must be tested, and error conditions are very hard to test. Keeping the number of thrown exceptions to three or less greatly simplifies your testing effort.
  • Cyclomatic Complexity - Cyclomatic Complexity (CC) is a measure of the decision logic in a method. The more decisions your method has, the more ways it will behave. Keeping the number of CC paths to 10 or less greatly reduces the risk of defects as well as increases the overall testability of your code.
  • Lines of Code - One of the oldest and simplest metrics used to measure a method's testability. A shorter method is easier to understand and test.
  • Paths - This metric looks at distinct data paths. Data paths are paths that link a data element's definition to its use. In other words, if you define a data element, you should use it, and if you use it, you should test it. Data paths often overlap with Cyclomatic Complexity paths.
  • Static Invocations - Methods under test invoke methods from external classes, and these external classes can usually be mocked or dummied up to behave exactly as required for an individual unit test. Static invocations of external methods often have an unchangeable behavior that thwarts even the best testing effort. Avoid this unnecessary coupling to external classes, and keep your external static invocations to a minimum.
  • Anonymous Classes - Anonymous classes make unit testing difficult because they exist only within the method under test, and cannot themselves be unit tested. Although anonymous classes are convenient (especially for GUI programming), their lack of testability and mockability can hinder your testing effort.

Labels: , ,

0 Comments:

Post a Comment

<< Home