JUnit 4.x style tests and test suites handle this differently than JUnit 3.x test suites.
TL;DR: you should set fields to null in JUnit3-style tests but you do not need to in JUnit4-style tests.
With JUnit 3.x style tests, a TestSuite
contains references to other Test
objects (which may be TestCase
objects or other TestSuite
objects). If you create a suite with many tests, then there will be hard references to all of the leaf TestCase
objects for the entire run of the outermost suite. If some of your TestCase objects allocate objects in setUp()
that take up a lot of memory, and references to those objects are stored in fields that are not set to null
in tearDown()
, then you might have a memory problem.
In other words, for JUnit 3.x style tests, the specification of which tests to run references the actual TestCase
objects. Any objects reachable from a TestCase
object will be kept in memory during the test run.
For JUnit 4.x style tests, the specification of which tests to run uses Description objects. The Description
object is a value object that specifies what to run, but not how to run it. The tests are run by a Runner
object that takes the Description
of the test or suite and determines how to execute the test. Even the notification of the status of the test to the test listener uses the Description
objects.
The default runner for JUnit4 test cases, JUnit4, keeps a reference to the test object around only for the duration of the run of that test. If you use a custom runner (via the @RunWith
annotation), that runner may or may not keep references to the tests around for longer periods of time.
Perhaps you are wondering what happens if you include a JUnit3-style test class in a JUnit4-style Suite? JUnit4 will call new TestSuite(Class)
which will create a separate TestCase
instance per test method. The runner will keep a reference to the TestSuite
for the entire life of the test run.
In short, if you are writing JUnit4-style tests, do not worry about setting your test case's fields to null
in a tear down (do, of course, free resources). If you are writing JUnit3-style tests that allocate large objects in setUp()
and store those objects in fields of the TestCase
, consider setting the fields to null
.