testng - 有没有办法在 After 方法中使用 ITestResult 获取完整的错误/异常?
问题描述
@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 获取完整的错误/异常?
解决方案
如果事情没有通过 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 中的异常详细信息视为失败。
推荐阅读
- javascript - TypeError:无法在 hanldeClick 处读取 null 的属性(读取“样式”)
- django - Django - 在查询集中计数和过滤
- java - 组合字符串及其反向的递归方法
- java - 如何将测试容器中的视频记录放置到 allure-report
- asp.net-mvc - 如何将数据从 DTO 映射到导航属性?
- php - 使用具有特定规则的正则表达式捕获文本
- java - 无法从 Maven 命令行调用黄瓜 junit 测试
- jquery - 更改增加和减少按钮的值时如何检测ajax的变化?
- vue.js - Vue Jasmine:两种不同的触发点击方式导致不同的结果
- python - 删除特定单词周围的特定行数