6. Annotation Type AfterClass:
If you allocate expensive external resources in a BeforeClass method you need to release them after all the tests in the class have run. Annotating a public static void method with @AfterClass causes that method to be run after all the tests in the class have been run. All @AfterClass methods are guaranteed to run even if a BeforeClass method throws exception. The @AfterClass method declared in superclasses will be run after those of the current class
Here is a simple example:
public class Example{
DatabaseConnection database;
@BeforeClass
public static void login(){
database = ...;
@Test
public void something(){
...
}
@Test
public void somethingElse(){
...
}
@AfterClass
public static void logout(){
database.logout();
}
}
Example in Eclipse:
import java.util.Date;
public class Person2{
private Date birthday;
private String name;
public Person2(String name, Date birthday){
this.name = name;
this.birthday = birthday;
}
public Person2(String name){
this.name = name;
}
public Date getBirthday(){
return birthday;
}
public void setBirthday(Date birthday){
this.birthday = birthday;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
if(this.birthday == null return 0;
Date now = new Date();
return now.getYear() - this.birthday.getYear() + 1;
}
}
Here is the test code which is used to test class Person2.
import org.junit.*;
import java.util.Date;
import java.text.SimpleDateFormat;
public class Person2Test extends Assert{
public static SimpleDateFormat df;
private Person2 person2;
@BeforeClass
public static void BeforeClass(){
df = new SimpleDateFormat("yyyy-mm-dd");
System.out.println("BeforeClass");
}
@Before
public static void setUp() throws Exception{
Date date = df.parse("2010-10-14");
Person2 = new Person2("Jimmy", date);
System.out.println("setUp");
}
@Test
public void getAge(){
assertEquals(person2.getAge(), 6);
System.out.println("Test getAge");
}
@Test
public void getName(){
assertEquals(person2.getName(), "Jimmy");
System.out.println("Test getName");
}
@After
public void tearDown() throws Exception{
person2 = null;
System.out.println("tearDown");
}
@AfterClass
public static void BeforeClass(){
df = null;
System.out.println("AfterClass");
}
}
No comments:
Post a Comment