0

検索値を入力し、返された検索結果から特定の結果を検索する C# で記述された Selenium テスト スクリプトがあります。私の問題は、結果の文字列で「null 参照例外」が発生し続けることです。紛らわしいのは、文字列をコンソール (単純な 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が null の場合Contains、null 参照例外がスローされます。それはあなたの症状に合うでしょう(コンパレータには値がありますが、それでもヌル参照例外が発生します)。

String.Contains

Note in the Exceptions section that ArgumentNullException is thrown if value is null, for Contains(value).

A safer way to code that for .Net 4.0 and later would be

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

or

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

for earlier .Net versions.

于 2013-05-28T20:58:31.517 に答える