0

我有一个用 c# 编写的 Selenium 测试脚本,它输入搜索值,然后从返回的搜索结果中查找特定结果。我的问题是我在结果字符串上不断收到“空引用异常”。令人困惑的是,如果我将字符串输出到控制台(简单的 Console.WriteLn 语句),它会很好地打印字符串。只有当我尝试对字符串执行某些操作时才会引发异常。任何想法为什么会发生这种情况?

相关代码如下:

IWebElement listElement2 = driver.FindElement(By.ClassName("FixedTables"));
itemsList = new List<IWebElement>(listElement2.FindElements(By.TagName("a")));
foreach (IWebElement item in itemsList)
{
    string comparator = item.GetAttribute("onclick");
    Console.WriteLine(comparator);//this works to print the string....
    //if (comparator.Contains(somestring))//this fails and throws the exception
    //{
    //    item.Click();
    //    break;
    //}
}

编辑:我将代码更改为如下所示:

    string comparator = item.GetAttribute("onclick");
    Console.WriteLine(comparator);
    if (comparator == null) Console.WriteLine("Is Null");
    if (somestring == null) Console.WriteLine("Somestring is Null");

这是我从控制台的输出:

get_emp_risk_details('560', '');

一片空白

get_emp_risk_details('490', '');

一片空白

4

1 回答 1

0

如果somestring为空,Contains将抛出空引用异常。这符合你的症状(比较器有一个值,但你仍然得到一个空引用异常)。

字符串.包含

ArgumentNullException请注意,如果 value 为 null,则抛出Exceptions 部分,对于Contains(value).

为 .Net 4.0 及更高版本编写代码的更安全方法是

if (comparator == null) {
    Console.WriteLine("comparator="+comparator);
} else {
    if ((!String.IsNullOrWhiteSpace(somestring)) && comparator.Contains(somestring)) }
    item.Click();
    break;
}

或者

if ((somestring != null) && (somestring.Length > 0)
    && comparator.Contains(somestring))
{
    item.Click();
    break;
}

对于早期的 .Net 版本。

于 2013-05-28T20:58:31.517 回答