Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit: Calling @After to set object to Null

Tags:

java

junit

Assume I have the following simple JUnit test

private Person person;

@Before
public void createObject()
{
   String firstName = "John";
   String lastName = "Doe";

   person = new Person(firstName, lastName);
}

@Test
public void test1()
{
   assert(firstName.equals("John"));
}

@Test
public void test2()
{
   assert(lastName.equals("Doe"));
}

Should I have an @After method that sets person = null?

I tried a similar test without the @After method and I can't seem to figure out it putting it in there has any advantages or disadvantages.

Ignore that the test names aren't very meaningful. I was just posting a simple example.

like image 430
Rhs Avatar asked Dec 11 '22 05:12

Rhs


2 Answers

You can, but it makes no sense. @Before method is invoked before every test run. Person will be GCed with and without @After.

like image 175
Alexey Malev Avatar answered Dec 23 '22 22:12

Alexey Malev


No, that's useless. Once the test is done, the test class instance goes out of scope, and becomes eligible to GC. Your test, and its person, will thus be garbage collected if the VM decides so.

You typically use @After like you would use a finally block: to close resources that need to be closed whatever the result of a test method.

like image 30
JB Nizet Avatar answered Dec 23 '22 21:12

JB Nizet