Jan302012

Structuring Unit Tests

One of the most troubling parts of unit testing, to me, is keeping things organized. For the past year, I've been managing my tests like this:

  • Every class has a tester class; for example, MyClass would have MyClassTests
  • In MyClassTests, multiple test methods would be setup to test each of the methods in MyClass
  • Test names would be in this format: MethodName_Scenario_ReturnValue

Tests for large classes would get out of control! There could be several test methods for a single method on the original class. Imagine a tester class if the original class had 20 methods.

However, thanks to this excellent tip from Phil Haack, this situation can be cleaned up and put into an easier to manage form.

By structuring your unit test classes to contain nested classes, each designated to test a single function, you can have a set of tests look like this:

For a further explanation, I would highly recommend reading Phil's post: Structuring Unit Tests. I'm going to be trying this out with my testing environment (I use nunit) over the next few weeks.