Skip to content

Writing tests loosely coupled with environment :

November 20, 2009
tags: ,

For better testing, follow – “Simulate things rather than recreating it”.

Suppose we want to test the condition for non existence for file, usally we will pass some invalid filenames and try to catch the exception. This is a  good short cut and it works fine.

class ReadFileTestCase extends TestCase{

public void testFileDoesNotExist(){
try{
Encoder encoder=new Encoder(reader);
encoder.encode(new File(“c:\invalidFile”));
}catch(FileNotFoundException fef){

}
}
}

The problem is,we are recreating the situation and not simulating it. Here, it works well in your environment. When the code is moved to another machine which contains a file named as invalidFile, then the test fails. It may lead to confusions as the test fails not because of code but of more dependency on the environment.

To avoid that, create a mock which will throw the invalid file name exceptions for whatever objects you pass.

class ReadFileTestCase extends TestCase{

public void testFileDoesNotExist(){
ReaderMock mock =new ReaderMock();
mock.setInvalidFiles();
try{
Encoder encoder=new Encoder(mock);
encoder.encode(new File(“c:\myFile”));
}catch(FileNotFoundException fef){

}
}
}

Thats it. The test will pass for all inputs and on all environments.

Advertisements
One Comment leave one →
  1. January 8, 2010 2:34 am

    Hey, ok, I get it, I guess – but does this really work?

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: