有没有办法在 After 方法中使用 ITestResult 获取完整的错误/异常?

问题描述 投票:0回答:2
@Test(priority = 16, enabled = true)
    public void C2410859_FilterAlertsByCard()
            throws IOException, InterruptedException, ATUTestRecorderException, APIException {

        record.start();
        launchUrl();
        startResult();
        startTestCase(Thread.currentThread().getStackTrace()[1].getMethodName().toString());
        LoginApplication(username, password);
        HomePage homePage = new HomePage();
        homePage.MyAlerts.click();
        MyAlerts myalerts = new MyAlerts();

    }




    @AfterMethod
    public void afterMethod(ITestResult result) throws ATUTestRecorderException {
        resultOfTest(result);   
        endTestcase();
        endResult();
        record.stop();
        closeBrowsers();
    }

测试结果:

public static void resultOfTest(ITestResult result) {
        try
         {
            if(result.getStatus() == ITestResult.SUCCESS)
            {

                //Do something here
                System.out.println("passed **********");
            }

            else if(result.getStatus() == ITestResult.FAILURE)
            {
                 //Do something here
                System.out.println("Failed ***********");
                test.fail("This test is failed due to "+ result.getThrowable());

            }

             else if(result.getStatus() == ITestResult.SKIP ){

                System.out.println("Skiped***********");

            }
        }
           catch(Exception e)
           {
             e.printStackTrace();
           }
    }

这只显示一个线性错误(例如,空指针异常)。有没有办法在 After 方法中使用 ITestResult 获得完整的错误/异常?

testng
2个回答
3
投票

如果 try catch() 块没有处理事情,您可以通过 ITestResult 对象在 AfterMethod 中获取它。

示例:

异常类型:java.lang.ArithmeticException:/零

@Test
public void testDemo() {
    int i;
    i = 9 / 0;
}

@AfterMethod
public void afterMethod(ITestResult result) {
    if (result.getStatus() == ITestResult.FAILURE) {
            String testResult = result.getThrowable();
            System.out.println(testResult);
    } 
}

这里 testDemo 方法因算术异常而失败,所以 ITestResult 有失败方法。通过使用

result.getThrowable();
方法你可以有异常描述。

但是,如果事情是由 try-catch() 块处理的,您就不能在 AtferMethod 中获得异常详细信息。

@Test
public void testDemo() {
    try {
        int i;
        i = 9 / 0;
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@AfterMethod
public void afterMethod(ITestResult result) {
    if (result.getStatus() == ITestResult.FAILURE) {
            String testResult = result.getThrowable();
            System.out.println(testResult);
    } 
}

这里的事情由 try-catch 块处理,所以它不会失败,测试方法成为通过。因此,您不能将 ITestResult 中的异常详细信息视为失败。


-1
投票

谢谢这帮我解决了问题。干得好

© www.soinside.com 2019 - 2024. All rights reserved.