【发布时间】:2021-11-25 01:50:27
【问题描述】:
我需要一种使用对象或变量的方法,它位于 try/catch 内部,try/catch 外部。
我在 blazor 网页上使用 selenium 进行自动化测试。
网页上有一个元素,它确实会动态更改其名称。
我现在的想法是:
在 100 种情况下的 99 种情况下,它总能找到名为 selector 的变量,这意味着没有抛出异常。在这种情况下,我想在 try/catch 之外使用对象 Field。
但在一种情况下,网页上有一个元素//div[@class='ql-editor']//p 在测试期间将其名称更改为//div[@class='ql-editor ql-blank']//p。现在,在测试抛出异常之前,它应该检查 //div[@class='ql-editor ql-blank']//p 是否可见。
如果是,那么我想使用 try/catch 之外的 catch 块中的对象 Field。
如果不是,它应该给我一个异常
注意:我知道这样一个事实,我认为解决该问题的方法可能不是最好的。我只是想防止只为 100 例中的 1 例创建另一种方法。
try
{
IWebElement Field = webDriver.FindElement(By.XPath(selector));
Field.SendKeys(textToType);
}
catch (Exception e)
{
IWebElement Field = webDriver.FindElement(By.XPath("//div[@class='ql-editor ql-blank']//p"));
Field.SendKeys(textToType);
}
string checkText = Field.GetAttribute("value");
string checkInstruction = Field.Text;
【问题讨论】:
-
只在尝试之外声明
Field,但没有值:IWebElement Field;。请注意,您还可以将调用 SendKeys 移动到 try...catch... 之后,以避免代码重复。 -
谢谢我试一试
-
我已将其发布为答案,以防我不清楚:)
标签: c# selenium selenium-webdriver selenium-chromedriver