Selenium Webdriver Testng : 如何在断言中失败测试并在报告中发送有意义的消息而不是"Nosuchelementexception"跟踪



他们在互联网上有很多资源,但我找不到简单的答案来解决我的问题。

我希望我的测试用例失败,并报告一行有意义的消息,而不是完整的堆栈跟踪。

我尝试过使用try、catch、if、else,但我希望我的测试失败,不要传递和抛出消息。

场景-加载url,如果url没有加载,则抛出错误并中止测试,然后转到加载下一个url 的下一次迭代

有什么解决方案吗?

您可以尝试。。。try catch

try {
doStuff();//this code is failing
}
catch (YourExpectedException e){ //catch the correct exception here
//this passes your custom message AND the caught exception
//should also stop the test
throw new AssertionError("This is my custom message", e); 
}

有两种方法。我想向您推荐最简单、最漂亮的方法。

1( 检查异常,如果您指定的异常,您将执行一些代码或执行一些操作。以下是示例:

@AfterMethod
public void afterMethod(ITestResult result) throws IOException {
Throwable exception = result.getThrowable();
if (exception instanceof org.openqa.selenium.TimeoutException
||
exception instanceof org.openqa.selenium. NoSuchElementException) {
Assert.fail("Some message or code");
}
}

2(您可以在项目中实现WebDriverEventListener

这意味着什么?

这意味着WebDriver允许在一些事件之前和之后执行一些逻辑。您可以在方法的实现中添加try-catch。

示例:

@Override
public void beforeFindBy(By by, WebElement webElement, WebDriver webDriver) {
// your code
}
@Override
public void afterFindBy(By by, WebElement webElement, WebDriver webDriver) {
// your code
}
@Override
public void beforeClickOn(WebElement webElement, WebDriver webDriver) {
// your code
}
@Override
public void afterClickOn(WebElement webElement, WebDriver webDriver) {
// your code
}

这里有一个更详细的例子:链接

相关内容

最新更新