Code Design for Testing

We all know we need to write unit test cases and in most cases we end up using a mocking framework like jmock, easymock or rmock for that, but do we really need to design our code to test? Unfortunately the answer is yes. We need to design our code in such a way so that it is easy to test (TDD or otherwise).

Here are some of the things which I keep in mind while coming up with the test enabled code.

  • Always use composition rather then inheritance – This is a good practice anyway but becomes all more important when we want to test our code as there is no way to mock call to super().

 

  • Avoid singletons, static and factory pattern – Instead use dependency injection framework (Guice or Spring) to inject dependencies rather then keeping the responsibility of dependency creation within the class.

 

  • Avoid extreme encapsulation – Do not keep things private and final instead make it package protected. This allows text cases to override methods.