Reputation: 31
I created few static variables in @BeforeClass
. Should I set them to null in @AfterClass
? These are non IO related objects.
Example:
public class ClassTest{
private static String staticText;
@BeforeClass
public static void setUp(){
staticText="long text";
}
//test methods
//Is this necessary
@AfterClass
public static void tearDown(){
staticText=null;
}
}
Upvotes: 3
Views: 3976
Reputation: 21663
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.
Upvotes: 9
Reputation: 23
Static variables stay in existance until the JVM terminates. If there is a reason to make it static (it's used by multiple tests and is costly to initializes) then feel free to do so, just clean them up when you are done with them.
For non-static, as others have said, JUnit will clean these up on its own.
Upvotes: 2
Reputation: 14530
good tests don't have to clean after themselves. they should only prepare data. other tests shouldn't depend on those data. in practice sometimes you need to close database connection or clean up some other long term resources. however some purists would say in that case it's not unit test any more. if you work with badly designed legacy code sometimes you have to clean some static variables of framework you use (e.g spring SecurityContext). usually such code can be refactored to avoid such cleaning
Upvotes: 0