Selenium - NoSuchElementException错误检查 [英] Selenium - NoSuchElementException error checking

查看:135
本文介绍了Selenium - NoSuchElementException错误检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在每个测试用例结束时,我通过调用以下代码来检查是否存在错误。我的问题是,即使不存在错误,代码将抛出一个 NoSuchElementException ,并将失败的测试用例。如果出现错误,测试用例将通过。

At the end of every test case I am checking to see if an error is present by calling the following code. The problem I have is even if an error is not present the code will throw a NoSuchElementException and will fail the test case. If the error is present the test case will pass.

如何修改我的代码,如果测试将不会出现错误,如果出现错误,测试用例将失败。

How can I modify my code so if an error is not present the test will pass and if an error is present the test case will fail.

public static void chk_ErrorIsNotEnabled()
{
    try
    {
        element = driver.findElement(By.id("ctl00_Content_ulErrorList"));
        if(element.getText().equals(""))
        {
            Log.info("Warning error is not dispayed." ); // The test should pass if element is not found
        }
        else
        {
            Log.error("Warning error is dispayed when it shouldnt be.");
        } //The test should fail if element is found
    }
    catch (NoSuchElementException e){}
}


推荐答案

问题是元素不存在, selenium throws NoSuchElement 异常,最终捕获 catch 块,而您的代码期望具有此ID的元素 ctl00_Content_ulErrorList 。您不能在不存在的元素上获取文本。

The issue is the element is not present and selenium throws NoSuchElement exceptions which eventually catch the catch block while your code expect an element with this id ctl00_Content_ulErrorList. You cannot get text on an element which does not exist.

一个很好的测试将如下所示:
注意 findElements ()这里。它应该找到具有错误列表的元素的大小。如果超过 0 你知道错误出来并且测试失败

A good test will be something like the following: Notice the findElements() here. It should find the size of the elements with error list. If that is more than 0 you know that errored out and test should fail

if(driver.findElements(By.id("ctl00_Content_ulErrorList")).size() > 0){
    Log.error("Warning error is dispayed when it shouldnt be.");
}else{
    //pass
    Log.info("Warning error is not dispayed." ); // The test should pass if element is not found
} 

这篇关于Selenium - NoSuchElementException错误检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆