注意:我无法粘贴确切的框架和代码,因为我工作的服务器无法从外部访问。因此,我将尝试用简单的语言和示例来解释我的问题。
概述 - 我创建了一个 Selenium 自动化框架,其中包括 TestNG、Maven (POM.XML)、测试数据文件、脚本和一些可重用函数。
我面临的问题 - 我使用 Jenkins 来执行我的脚本。 Jenkins 调用 POM.XML 文件,POM.XML 文件又调用 testng.xml 文件(在 testng.xml 文件中,我提到了要执行的脚本)
假设我必须执行登录操作
主要脚本
@Test
Public void maintest ()
{
//I use Extent reports for reporting purpose and hence I have created extent
//reporting reusable function which is called in the below fashion.
//If Login method returns pass, ExtentReportingFunc passes Pass to its
//function and displays Pass for that particular Login step in the report.
ExtentReportingFunc (Login(UserName, Password));
}
可重用函数
Public String Login (String UN, String Pass)
{
//Sendkeys and set UN
driver.findelement (By.id("username")).sendkeys(UN);
//Sendkeys and set Password
driver.findelement (By.id("password")).sendkeys(pass);
//Click Login
driver.findelement (By.id("login")).click ();
//Verifying the message "Welcome User" is displayed after login
try
{
if (driver.findlement (By.id("welcomemessage")).isdisplayed ();
{
return pass;
}
} catch (Exception e)
{
//If welcome message is not found then return fail to the Reporting function
return "fail";
//Below code will be unreachable which is correct as per Java but that is the challenge.
// I tried several ways to find a work around to return fail as above as
// well throw exception but no luck till now.
// Upon throwing exception in the below way, Jenkins displays build as
//failed. If it is not done, though the script has failed,
//Jenkins displays "BUILD PASSED"
throw e;
}
}
//Extent Reporting function
ExtentReportingFunc (String status)
{
log.report (status);
}
这里的挑战是 - 在 catch block 中,如果我不提及“throw e”,Jenkins 将无法理解已发生故障并在其控制台输出中显示“BUILD PASSED”。我希望它在 Jenkins 控制台中显示“构建失败”。我希望它显示“BUILD FAILED”的原因是 - 我已将 JIRA 与 Jenkins 集成。仅当 jenkins 显示 BUILD FAILED 时,它才会自动将错误记录到 JIRA。如果它是“BUILD PASSED”并且虽然完成状态是 UNSTABLE,Jenkins 的测试结果部分不会显示任何失败,也不会在 JIRA 中记录任何错误。
但是,那时我将无法将 return“fail”传递给主报告函数,以便它可以在报告中将登录步骤显示为失败。
我明白,根据 JAVA,我们可以在 catch block 中抛出或返回,但不能同时执行两者。我们还有其他方法可以完成这项工作吗?
我已经创建了端到端框架,但后来当我开始与 Jenkins 集成时意识到这个问题(否则直到那时一切都很好)。
最佳答案
为什么不在 catch 语句中添加断言失败,这样就可以强制 testng 测试在 catch 语句中失败
org.testng.Assert.fail(“我在这里失败了,因为......你可以在这里添加你的电子邮件”);
只需在前面添加一行代码即可
return "fail";
并保持函数的其余部分不变
关于java - 即使由于脚本中的错误处理(try 和 catch block )导致测试失败,Jenkins 也会显示 "Build Success",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54558613/