Reputation: 733
In the below example before class method is running twice. Is it the expected behavior? Because beforeClass is supposed to run only once before the first method in class runs. But in my class it runs twice.
package test;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
public class Sample1
{
@BeforeSuite
public void setUp()
{
System.out.println("This is before suite");
}
@BeforeTest
public void init()
{
System.out.println("This is before Test");
}
@BeforeClass
public void t1()
{
System.out.println("This is before class");
}
@BeforeMethod
public void t3()
{
System.out.println("This is before Method");
}
@AfterMethod
public void t4()
{
System.out.println("This is After Method");
}
@AfterClass
public void t2()
{
System.out.println("This is After class");
}
@AfterTest
public void cleanUp()
{
System.out.println("This is After Test");
}
@AfterSuite
public void tearDown()
{
System.out.println("This is after suite");
}
}
package test;
import org.testng.annotations.Test;
public class Sample2 extends Sample1 {
@Test
public void f()
{
System.out.println("This is the testmethod1 in Sample2");
}
@Test
public void tets1 ()
{
System.out.println("This is the testmethod2 in Sample2");
}
}
<suite name="Suite1" verbose="1" >
<test name="Regression1" >
<classes>
<class name="test.Sample2">
<methods>
<include name = "f" />
</methods>
</class>
</classes>
</test>
<test name="Regression2" >
<classes>
<class name="test.Sample2">
<methods>
<include name = "tets1" />
</methods>
</class>
</classes>
</test>
</suite>
/* Output is below -- after and before class running twice
This is before suite
This is before Test
This is before class
This is before Method
This is the testmethod1 in Sample2
This is After Method
This is After class
This is After Test
This is before Test
This is before class
This is before Method
This is the testmethod2 in Sample2
This is After Method
This is After class
This is After Test
This is after suite
*/
Upvotes: 0
Views: 2344
Reputation: 159086
You get that behavior because your <suite>
XML runs the two test methods as independent tests. If you allowed a single test to run both methods, then they would run on the same class instance, and @BeforeClass
would only run once.
Upvotes: 1