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?
The setUp() method is JUnit���s primary means for setting up test data fixtures in preparation for the execution of a test method ( tearDown() is for cleaning up fixtures after a test method completes).
Prepare and Tear Down State for a Test Class XCTest runs setUp() once before the test class begins. If you need to clean up temporary files or capture any data that you want to analyze after the test class is complete, use the tearDown() class method on XCTestCase .
JUnit creates all the TestCase instances up front, and then for each instance, calls setup(), the test method, and tearDown(). In other words, the subtle difference is that constructors are all invoked in batch up front, whereas the setUp() method is called right before each test method.
As outlined in Recipe 4.6, JUnit calls setUp( ) before each test, and tearDown( ) after each test. In some cases you might want to call a special setup method once before a series of tests, and then call a teardown method once after all tests are complete.
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.
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 Closable
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With