TestNG 如何在测试失败时执行 beforeclass() 方法

TestNG How to execute beforeclass() method on testfailure

我在 beforeclass() 中有登录步骤,之后测试开始执行。如果测试失败,应该重新调用 beforeclass() 方法。我正在使用测试监听器 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          
    }
      
}

你可以在@AfterMethod中知道测试的结果,所以如果失败了,那么你可以在after方法中重复逻辑。在这种情况下不需要测试侦听器。

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

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

    // login
}