Design for testability

I like working with unit tests but I find it quite hard to implement fast and isolated tests in real world software. I got some great guidance on this topic attending this years EMEA Tech Ed.

  • Pass dependent classes via constructor. When this gets too much, because you end up with really long constructors you should use dependency injection. For this purpose the Unity Application Block from the Enterprise Library (Microsoft) serves well.
  • Try to avoid singletons and static methods.
  • Isolate dependent classes by using mock objects. E.g. Rhino Mocks is an excellent tool to create Stubs and Mocks, type-safe.
  • If you cannot mock an object because it is sealed (such as most classes in SharePoint object modell) use the Typemock Isolator tool.
  • Give your test methods useful names such as MethodUnderTest_InputProvided_ExpectedResult and use typically one Assert statement per test.
  • Be aware of whether you are writing a unit test or an integration test. I use a folder for each in test projects to make the intention clear to everyone.

Since I picked-up working this way I am writing faster and better unit tests.

Leave a Reply

Your email address will not be published. Required fields are marked *