我们可以在 testNG 中处理 try 和 catch 中的断言失败吗

Can we handle Assert fail in try and catch in testNG

我正在尝试使用 selenium webDriver + TestNG 自动化应用程序。

其中我使用了多个断言语句,例如 Assert.assertEquals("Dhaval", "Dhaval1");

我正在尝试使用 try& catch 块捕获 assertionfail 异常。 因为我正在为测试结果填写 excell sheet。

但是任何当断言失败时应用程序直接停止执行并且catch块将不会执行。

任何建议。

提前致谢!!!!

试试这个:

try {
Assert.assertEquals("Dhaval", "Dhaval1");
}
catch (AssertionError e) {
Assert.assertEquals("Dhaval", "Dhaval");
}

如果您在测试方法中处理测试结果以将其保存到电子表格中,那么您的做法很糟糕。在这里查看以取消此操作:http://www.techbeamers.com/save-selenium-webdriver-testng-result-excel/

否则,如果您确实需要这样做:

try {
    Assert.assertNotEquals(actualValue, expectedValue);
} catch (Exception e) {
    // Thread the excpetion here
}

在测试断言上捕获异常是一种不好的做法,它们是断言是有原因的。 您要做的是实现自定义 ITestListener 并在 onTestFailure(ITestResult result) 方法中定义所需的逻辑,如果 case 失败,将执行此方法中的代码。