Friday, February 09, 2007

Unit Test Granularity

How many assertions should I have in my automated Unit Tests?


Unit Tests are Methods Too


Test cases just like methods in your code. They should be designed using the smae principles. Specifically, a method should be highly cohesive. It's purpose should be focused and well defined. Test cases are no exception. A test identifies and verifies a specific scenario with the intention of revealing a defect. An automated unit test method with proper cohesion must have this single-minded focus. It may be somewhat extreme to demand 1 assert per test. The single assertion test is however and good ideal to strive for.


Many Tests Make Light Work


While the purpose of your existing tests is to catch regression. They can also be useful helping determine the cause of introduced errors. A group of test failures are more likely to point to a cause than a single test, due to the simple volume of information. Looking at a group of failed tests raises the question 'why are these tests failing, what do they have in common?' A single failed test immediately becomes a debugging effort


Read this MSDN Unit Testing Article for some good unit testing guidelines.