I was intrigued by the answer to a similar question. I believe it is incorrect. So I created some test code. My question is, does this code prove/disprove/inconclusive the hypothesis that it is useful to nullify member variables in teardown methods? I tested it with JUnit4.8.1.

JUnit creates a new instance of the test class for each of the 4 tests. Each instance contains an Object obj. This obj is also inserted as the key of a static WeakHashMap. If and when JUnit releases its references to a test instance, the associated obj value will become weakly referenced and thus eligible for gc. The test tries to force a gc. The size of the WeakHashMap will tell me whether or not the objs are gc'ed. Some tests nullified the obj variable and others did not.

import org . junit . Before ;
import org . junit . After ;
import org . junit . Test ;
import java . util . ArrayList ;
import java . util . WeakHashMap ;
import java . util . concurrent . atomic . AtomicInteger ;
import static org . junit . Assert . * ;

public class Memory
{
    static AtomicInteger idx = new AtomicInteger ( 0 ) ;

    static WeakHashMap < Object , Object > map = new WeakHashMap < Object , Object > ( ) ;

    int id ;

    Object obj ;

    boolean nullify ;

    public Memory ( )
    {
    super ( ) ;
    }

    @ Before
    public void before ( )
    {
    id = idx . getAndIncrement ( ) ;
    obj = new Object ( ) ;
    map . put ( obj , new Object ( ) ) ;
    System . out . println ( "<BEFORE TEST " + id + ">" ) ;
    }

    void test ( boolean n )
    {
    nullify = n ;
    int before = map . size ( ) ;
    gc ( ) ;
    int after = map . size ( ) ;
    System . out . println ( "BEFORE=" + before + "\tAFTER=" + after ) ;
    }

    @ Test
    public void test0 ( )
    {
    test ( true ) ;
    }
Edit
Report