JUnit: Calling @After to set object to Null

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.

Answer

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

Leave a Reply

Your email address will not be published. Required fields are marked *