Lambda Expression C#中的OpenQA.Selenium.NoSuchElementException

时间:2014-04-06 02:47:28

标签: c# selenium lambda

我正在调试一个项目,并且在调试时已经收到NoSuchElementExceptions,说“无法找到id为== txtUserId的元素”。问题是代码使用lambda表达式返回一个对象,因此很难捕获NoSuchElementExceptions,因为它使该对象超出了该方法的其余部分的范围。

try
{
   var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
   var itxtUserId = wait.Until(d => d.FindElement(By.Id("txtUserId")));

   //Clear the textbox 'UserID' then fill it with the user ID
   itxtUserId.Clear();
   itxtUserId.SendKeys("UserID");
}
catch (Exception exception)
{
   // I have code here to handle exceptions
}

我已阅读http://watirmelon.com/2014/01/23/checking-an-element-is-present-in-c-webdriver/,建议编写全局变量,这些变量是辅助方法,以防止这些类型的错误首先发生。但是,我听说许多开发人员对全局变量的使用不满意,并且可能会导致问题。此外,我觉得仍然需要能够处理异常,以便程序可以在运行时恢复正常。因此,如何处理Lambda表达式中的异常?有没有办法在没有Lambda表达式的情况下返回此对象?像这样的语句贯穿整个代码库,它们看起来像Selenium文档中的examples,但它们不断抛出异常。

这是“无法找到具有id == txtSearchByLastName的元素”的堆栈跟踪

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(1));
var textUserSearch = wait.Until(d => d.FindElement(By.Id(strElementId)));

at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecuteDictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementById(String id)
at OpenQA.Selenium.By.<>c__DisplayClass2.<Id>b__0(ISearchContext context)
at OpenQA.Selenium.By.FindElement(ISearchContext context)
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)
at Automation_Solution.Navigate.<>c__DisplayClassc.<PatientSearch>b__b(IWebDriver d) in c:\Users\username\Source\Workspaces\TestSuite\Solution\Solution\Navigation.cs:line 226
   at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)

2 个答案:

答案 0 :(得分:2)

听起来你已经&#34;打破所有抛出的异常&#34;在您的项目中设置。在Visual Studio中,从“调试”菜单中选择Exceptions...。在“例外”对话框中,确保选中“&#34; Thrown&#34;”下的复选框。未经检查。

Exceptions Dialog Screenshot

答案 1 :(得分:-1)

我认为这就是你所需要的:

var itxtUserId = wait.Until(d => d.FindElement(By.Id("txtUserId"))).ignoring(NoSuchElementException.class);

http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html

http://selenium.googlecode.com/git/docs/api/dotnet/html/AllMembers_T_OpenQA_Selenium_Support_UI_WebDriverWait.htm

相关问题