cbeust/testng — Issue #110: @AfterClass called before all tests from an instance are runned
Author: pouellet8d
Created: 2011-10-14 18:18:56+00:00
State: open

Why is that the expected behavior? A lot of our test fail because of this behavior. Our expectation of the AfterClass was that it was called once, after all the test of the instance are runned. Why? because the parent test setup some resources on which the child test depends on. So we may have this issue:

parent.beforeClass: setup some resources
parent.test
parent.afterClass: clean those resources
child.test: use those resources, but woups! Those resource are now cleaned.

@Test
public abstract class ParentTest {

//Resource should be something bigger than a string, like a network connection or initialization of a database schema.
protected String parentResource = null;

@BeforeClass
protected void beforeClass() {
parentResource = "initialized";
}

@AfterClass
protected void afterClass() {
//Free the resource
parentResource = null;
System.out.println( "parent after class" );
}

@Test
public void aparentTest() {
System.out.println( "parentTest" );
}
}

public class ChildTest extends ParentTest {

protected String childResource = null;

@BeforeClass
protected void beforeClass() {
super.beforeClass();
childResource = "initialized";
}

//I added a dependsOnMethods to force execution order. In my real life scenario, I don't have a dependsOnMethod, but the child's test are executed after the parent test.
@Test(dependsOnMethods = "parentTest")
public void z() {
System.out.println( "childTest" );
System.out.println( "parentResource length: "+ parentResource.length() );
}
}

java.lang.NullPointerException
at com.eightd.ftk.terminal.consistency.ChildTest.z(ChildTest.java:19)