java—如何捕获控制台中显示的Assert错误

wa7juj8i  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(686)

我使用assert来验证两个值,所以如果我的测试用例失败,并且在控制台中显示失败的原因(应该是[passwo],但是找到了[password])。我想捕获这个Assert错误,以便在excel工作表中编写这个错误消息。
我也尝试了try-catch块,但它也不起作用,下面是我的单Assert代码。

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);

    }
h79rfbju

h79rfbju1#

这个 java.lang.Throwable 类是java异常层次结构的根类,由两个子类继承: Exception 以及 Error . java异常类的层次结构如下所示:

执行Assert,相信是真的。如果失败,jvm将抛出一个名为assertionerror的错误。assertionerror类是inherit error类,因此可以使用throwable、error和assertionerror来捕获Assert错误
所以catch block应该是:

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

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

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

f4t66c6m2#

您应该捕获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);
    }

相关问题