Monday, January 10, 2011

JUnit Annotation Type - After

4. Annotation Type After:

If you allocate external resources in a Before method you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception. The @After methods declared in superclasses will be run after those of the current class.

Here is a simple example:

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

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

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

Example in Eclipse:

Create the class called Person in eclipse.

package test;

public class Person
{
       private String name;
    
       public Person(String name)
       {
             this.name = name;
       }

      public String getName()
      {
           return name;
      }
}

Here is the test cose which is used to test Person class.

package test;

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class PersonTest
{
        private Person person;

       @Before
       public void setUp() throws Exception{
               person = new Person("Jimmy");
               System.out.println("setUp");
       }

      @Test
       public void getName(){
                assertEquals(person.getName(), "Jimmy");
                System.out.println("Test getName");
       }

      @After
      public void tearDown() throws Exception{
               person = null;
               System.out.println("tearDown");
     }
}

Output:
setUp
Test getName
tearDown

No comments:

Post a Comment