如何捕获在控制台中显示的断言错误

时间:2020-01-24 21:10:58

标签: java selenium-webdriver testng

我正在使用assert来验证两个值,因此,如果我的测试用例失败并在控制台中显示了失败的原因(预期为[Passwo]但找到了[Password])。我想捕获此断言错误,以便可以在Excel工作表中写此错误消息。

我还尝试了try catch块,但它也无法正常工作,下面是我的单断言代码。

try {
        //Password
        String PasswordFromApplication;
         assertion.assertEquals(PasswordFromApplication=login.getPasswordNameLabel(), ReadValueFromID.getValue("LoginWindowPasswordLabelID"));

        String expectedKeyFromExcel2=ReadKeyFromID.getKeyValue("LoginWindowPasswordLabelID");

        String valueFromXml2=ReadXmlData.getValue(expectedKeyFromExcel2);

        assertion.assertEquals(PasswordFromApplication, valueFromXml2);

        System.out.println("LoginWindowPasswordLabelID PASSED");
    } catch (Exception e) {

        System.out.println("FAILED DUE TO "+e);

    }

2 个答案:

答案 0 :(得分:2)

java.lang.Throwable类是Java异常层次结构的根类,它由两个子类ExceptionError继承。 Java Exception类的层次结构如下:

enter image description here

执行断言,被认为是正确的。如果失败,则JVM 引发名为 AssertionError 的错误。 AssertionError类为 继承 Error 类,因此您可以使用 Throwable Error AssertionError 来捕获断言错误

所以捕获块应该是:

catch (AssertionError ae) {
        System.out.println("Assertion Error is  "+ae);
    }

OR

catch (Error e) {
        System.out.println("Assertion Error is  "+e);
    }

OR

catch (Throwable t) {
        System.out.println("Assertion Error is  "+t);
    }

答案 1 :(得分:0)

您应该捕获AssertionError而不是Exception,AssertionError不会从Exception继承(它继承自Error),这就是您的catch块未捕获到异常的原因。

工作代码:

try {
        //Password
        String PasswordFromApplication;
         assertion.assertEquals(PasswordFromApplication=login.getPasswordNameLabel(), ReadValueFromID.getValue("LoginWindowPasswordLabelID"));
        String expectedKeyFromExcel2=ReadKeyFromID.getKeyValue("LoginWindowPasswordLabelID");
        String valueFromXml2=ReadXmlData.getValue(expectedKeyFromExcel2);
        assertion.assertEquals(PasswordFromApplication, valueFromXml2);
        System.out.println("LoginWindowPasswordLabelID PASSED");
    } catch (AssertionError e) {
        System.out.println("FAILED DUE TO "+e);
    }