tags:

views:

71

answers:

2

I am reading one book about JUnit now and writer advises nulling resources in tearDown method. Why? Isn't this GC's job? Can it seriously make any harm?

Lets think of example like this:

public class SomeTest extends TestCase {
  Vector vector;
  List<Object> list;  

  protected void setUp() {
    vector = new Vector();
    list = new ArrayList<Object>();
  }

  // messing with resources
  // adding, deleting, testing whatever

  protected void tearDown() {
    vector = null;
    list = null;
  }
}

What do you think? Is that code in tearDown necessary?

+3  A: 

It depends what you consider a resource. Whilst heap space is a resource, you can probably get away with the GC cleaning up after you (YMMV).

Things that might cause issues are Closables like database connections / open files and streams etc. which should always be closed after use to prevent nasties in long running code.

I once had a situation that an integration test for some hibernate code didn't cleanup properly and resulted in some really strange errors. It took many hours to find and angered me so badly that I'll never make the same mistake again.

gpampara
I see this is the thing. Author should have written so :) So for example I posted above, it's useless, right ?
Xorty
Yes :) Your test case should be fine. I generally try to avoid @Before and @After cases - just do them where needed.
gpampara
If SomeTest was part of a very large TestSuite with many TestCases, and somes TestCases in that TestSuite create objects in setUp() that take up a lot of memory and do not null out the references in tearDown(), then yes, you could run low on memory while running the suite. Note that the answer is different for JUnit 4.x style tests.
NamshubWriter
+4  A: 

Yes, this can indeed be necessary.

You see, JUnit will actually create a separate instance of the Test class for each test method, and the Junit3 test runner (not so with JUnit4) will keep these instances around until the entire test suite has finished.

Therefore, if your (JUnit3) test class has fields that take up a lot of memory, you can easily run out of heap space when you have a large number of test methods. Of course, if those collections in your example code only ever contain a handful of short strings, it doesn't matter.

Michael Borgwardt
Interesting, I didn't know that each method uses own Test instance :O Thanx ...
Xorty
It's the same for JUnit 4.
Péter Török
Ok ... thanx everyone for help but this is most interesting answer for me, so I mark it as accepted.
Xorty
JUnit4 does indeed create a different object for each test method, but it will not keep these instances around until the entire test suite has finished. See my response to http://stackoverflow.com/questions/3655944/is-it-really-necessary-to-nullify-objects-in-junit-teardown-methods
NamshubWriter