The GOF Design Patterns book rarely mentions the test-ability of each pattern. I'm aware that there are patterns such as Singleton that would lead to code for which it is difficult to write unit tests, and some such as Strategy that help with TDD.

Which patterns promote TDD, and which hinder TDD?

2 Answers 2


Any pattern that promotes a functional approach (i.e. you pass it some value(s), it returns a value, and doesn't cause side effects) is going to be straightforward to test. Any pattern that causes side effects or persists state is going to be difficult to test, unless you can catch all of the side-effects and prove them. That's why user interfaces are difficult to test; you need a human being to eyeball the screen to see the side effects.

Singleton is not easy to test because it persists state, i.e. any functions you perform on it are not idempotent (your results may change each time). Databases are the same way; to unit test them properly, you have to wrap your tests in transactions so that you can roll them back after the test.

So go down the list of patterns, and evaluate each one on this basis. For example, the Abstract Factory pattern is testable, because you can test which type it returns. RAII should be testable because you can check the lifetime of an object by seeing if it is null. Garbage collection is not necessarily testable in the same way, since you don't always know when the garbage collector will decide to do a collection.


Test-ability of any code can be determined with the following: - is there any global state? (singleton has) - are there any hidden dependencies in the code? (IoC and dependency injection make your code testable) - is your class using new operator to create objects inside functions/constructors? if yes, code is not testable.

A rule of thumb would be to just check usage of new. More new you see in code, less testable the class is.

  • That's pretty much right, except that any aggregated structure the class itself creates becomes essentially part of the unit being tested, and all the tests of necessity have to be through the original class interface. The more complex this structure, the more states have to be tested for that unit. And if it is cyclical, that number could become effectively infinite (if not actually so). Dependency injection lets the tests isolate each piece of that structure, greatly reducing the combinatorial explosion of possible states.
    – kylben
    Oct 19, 2011 at 17:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.