Tuesday, August 11, 2009

Best Practice on Junit: Always set your fields to null on tearDown

This was a surprise to me today. Just wanted to share it thourgh a small blog entry, so maybe others are also going through the same thing.

Say you have this test:


public class MyTest extends TestCase
{

Server server;

public void setUp()
{
server = new Server();
}

public void testOne() throws Exception
{
System.gc();
Thread.sleep(1000);
}

public void testSecond() throws Exception
{
System.gc();
Thread.sleep(1000);
}

public void testThird() throws Exception
{
System.gc();
Thread.sleep(1000);
}
}


JUnit will hold one instance of MyTest for every method being executed. So if Server is a heavy weight object you will end up with three instances in the memory, until all the test methods on this class are executed.

So, as a best practice on unit tests aways set big objects such as server, connections or anything lilke that to null on a junit test.

No comments: