Interview Questions

When Do You Need to Write an @After Method?

JUnit Questions and Answers


(Continued from previous question...)

When Do You Need to Write an @After Method?

You need to consider the following points when anwering this question:

  • If there is no "@Before" method, you don't need to write an "@After" method. There is nothing to be released.
  • If the "@Before" method only creates Java internal objects, you don't need to write an "@After" method. Java internal objects will be released automatically by the Java garbage collector.
  • If the "@Before" method creates any external resources like files or database objects, you need to write an "@After" method to release those external resources.

Here is a good example of using "@After" methods from the JUnit FAQ:

package junitfaq;

import org.junit.*;
import static org.junit.Assert.*;
import java.io.*;

public class OutputTest {

    private File output;

    @Before
    public void createOutputFile() {
        output = new File(...);
    }

    @After
    public void deleteOutputFile() {
        output.delete();
    }

    @Test
    public void testSomethingWithFile() {
        ...
    }

    @Test
    public void anotherTestWithFile() {
        ...
    }
}

(Continued on next question...)

Other Interview Questions