Unit test structure guidelines

I have recently started to structure my unit tests differently and have to share. Prior to this new convention, things were messy. Let’s look at an example.

Let’s say there’s a class you need to test called WidgetController. This controller is supposed to be responsible for inserting, updating, and deleting Widgets. It has those 3 actions on it:

public class WidgetController
{
    public void Insert(Widget widget)
    {
        // Do something
    }
    public void Update(Widget widget)
    {
        // Do something
    }
    public void Delete(int widgetId)
    {
        // Do something
    }
}

Without the new method of unit test structure, I might have tested it this way:

[TestClass]
public class WidgetControllerTests
{
    [TestMethod]
    public void when_inserting_someassertion()
    {
    }

    [TestMethod]
    public void when_updating_someassertion()
    {
    }

    [TestMethod]
    public void when_deleting_someassertion()
    {
    }
}

This has the benefit of only using one class for all of the WidgetController tests, but this class can quickly grow. The new method I use:

public class WidgetControllerTests
{
    [TestClass]
    public class InsertTests
    {
        [TestMethod]
        public void someassertion()
        {
        }
    }

    [TestClass]
    public class UpdateTests
    {
        [TestMethod]
        public void someassertion()
        {
        }
    }

    [TestClass]
    public class DeleteTests()
    {
        [TestMethod]
        public void someassertion()
        {
        }
    }
}

With one assertion made, this looks cumbersome, but imagine when you have 15 different mini assertions for an insert test. Perhaps your business rules are fairly complex, and you need to verify different aspects through many different unit tests. This gives you the structure and separation to really get some good organization for your tests. The test UI and any test result reporting suites will be able to break your tests down by subclass, giving you a much better idea of what’s going on.