misterios
misterios

Reputation: 354

TestNG How to execute beforeclass() method on testfailure

I have login steps in beforeclass() and after that tests starts executing. If there is a test failure, beforeclass() method should be reinvoked. I'm using test listener class.

public class LoginTests {

    @BeforeClass
    public void beforeClass() throws Exception {
        System.out.print("login in application");        
    }    
      
    @BeforeMethod
    public void beforeMethod() {
            
    }     
      
    @AfterClass
    public void afterClass(){
      
    }     
      
    @Test
    public void test1() {
        System.out.print("go to first page");               
    }
    
    @Test
    public void test2() {
        System.out.print("go to second page");          
    }
          
    public void onTestFailure(ITestResult result) {       
        //if there is test failure run  beforeclass() method          
    }
      
}

Upvotes: 1

Views: 206

Answers (1)

Gautham M
Gautham M

Reputation: 4935

You could know the result of the test in @AfterMethod, so if it is failed, then you could repeat the logic in the after method. No need for test listener in this case.

@BeforeClass
public void beforeClass() throws Exception {
     //login
 }

@AfterMethod
public void afterMethod(ITestContext tc, ITestResult result) {
    if (result.isSuccess()) {
        return;
    }

    // login
}

Upvotes: 1

Related Questions