Short Answer:
For static members: For both JUnit3 and JUnit4, static members are never eligible for garbage collection unless you explicitly nullify their references (e.g. in an @AfterClass
method).
For non-static members: If you're using JUnit3, then it's good practice to nullify non-static member variables in your @After
method. If you're using JUnit4 with the default test runner, then this practice is unnecessary.
Long Answer:
JUnit creates a separate instance of your test class for each test method that exists in that class. JUnit3 keeps the references to all of these instances around until the test suite has completed execution, so it is good practice to clean up these references in your tearDown()
method. (Of course, since only one instance of a static variable exists across all instances of the class it belongs to, this is more important for non-static variables.)
JUnit4 still has the behavior of creating a separate instance of your test class for each test method, but as long as you're using the default test runner, then it only keeps a reference to the instance of your test class which the currently executing test belongs to. As a result, non-static member variables will be cleaned up even if you don't explicitly nullify them in your tearDown()
method.
Beware, however, that if you use a custom JUnit4 test runner (via the @RunWith
annotation), then there's no guarantee about how long it will keep around references to test class instances.