Skip to content

Good Testable code:

November 10, 2009

(Misko Hervey – Google Agile)

1. Composition is better than inheritance. Achieve code reusability by composition.

2. Subclassing for test is a code smell.

class SomeWork{

public void doWork(){
Object ob=new Object();
To test the above class,

Move the object creation to a factory method ie Extract

Override the extracted method in the test subclass

Return the mocked object int he overridden method
class SomeWork{
public void doWork(){
Object ob=createObject();
protected Object createObject(){
return new Object();


Hence the testing is done by,

class SomeWorkTest extends TestCase{
MockObject mockOb=new MockObject();

public void test() {
SomeWork somework = new SomeWork() {
protected Object createObject() {
return mockOb;

3. Law of Demeter – Pass objects which are needed. Dont expect the method to create the object. Decompose the class and method such that it has a single responsibility.

class SomeWork{
//not like this
public Somework(String fileName){
file file=new File(fileName);
//do some work

//Instaead use this
public Somework(File file){
//do some work

4. Make the dependencies explicit.(Dependency injection / Inversion of control) – Testing explicit dependencies is easier.
5. Difficulty of testing – (desc order) – construction -> Singleton -> Service Locator -> Dependency injection(objects passed in constructor). Dependency injection enforces order of initialization at compile time.
Advice:  Avoid global state and handle new operator with care
6. static values are hard to test. They are difficult when running test in parallel.
7. Use your own interface to wrap third party interfaces so that the interfaces can be mocked and your tests are easier and faster.

One Comment leave one →
  1. August 23, 2010 7:30 pm

    3. This results to more complex method calls. I believe we should keep both, changing the first to call the second method overload.

    Agree with others.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: