【发布时间】:2017-03-02 09:46:38
【问题描述】:
我正在尝试检查页面上是否存在具有给定类的DIV。这里的测试团队使用了一种模式,即查找元素,说明预期的内容,然后执行一个简单的 if-else,如下所示(仅用于解释下面的布局)。
如果我从var topNavClassName assignment 的末尾删除.ToString(),则if 语句中的相等检查报告Operator '==' 不能应用于IWebElement and string 类型的操作数。
但是当保留它并运行代码时,Write-line 会返回为: 错误:
我希望找到“container-fluid”的主导航 Div,但是 相反,我得到了 OpenQA.Selenium.Firefox.FirefoxWebElement
如何对预期内容和发现内容进行相等性检查?
public static void validateTopBarNavigationIsPresent()
{
var expectedTopNavClassName = "container-fluid";
// Find the navigation element container to check it loaded
var topNavClassName = Driver.Instance.FindElement(By.ClassName("container-fluid")).ToString();
Console.WriteLine($"The variable topNavClassName contains the value: {topNavClassName}");
// OR perhaps it's better to find it this way?
//IJavaScriptExecutor js = Driver.Instance as IJavaScriptExecutor;
//string topNavClassHTML = (string)js.ExecuteScript("return arguments[0].innerHTML;", expectedTopNavClassName);
//Console.WriteLine($"The variable url contains the value {topNavClassHTML}");
if (topNavClassName == expectedTopNavClassName)
{
Console.WriteLine($"I found the main navigation Div by its Class Name: {topNavClassName}");
}
else
{
Console.WriteLine("The main navigation Div was NOT located on the page");
var topBarNavigationException = $"I expected to find the main navigation Div of 'container-fluid', but instead I got {topNavClassName}";
TakeScreenshot.SaveScreenshot();
throw new Exception(topBarNavigationException);
}
}
编辑:作为注释,我尝试将 if (topNavClassName == expectedTopNavClassName) 更改为 if (topNavClassName != null) 并且我可以通过将 topNavClassName 类名字符串更改为 ("container-fluidssssss") 来使其失败,它会失败。所以似乎找到了一些东西。
更新
为了进一步调查我自己的问题,我修改了代码以简单地检查页面上是否存在所需的类名字符串。这行得通(显然?),但我仍然觉得最好实际抓住字符串作为更直观的证据 - 它存在并且符合预期。
这是备用代码:
public static void validateTopBarNavigationIsPresent()
{
bool topNavClassName = Driver.Instance.PageSource.Contains("container-fluid");
if (topNavClassName == true)
{
Console.WriteLine($"The check for 'container-fluid' being present came back as: {topNavClassName.ToString().ToUpper()}");
}
else
{
var topBarNavigationException = $"The check for 'container-fluid' being present came back as: {topNavClassName.ToString().ToUpper()} but I expected TRUE";
TakeScreenshot.SaveScreenshot();
throw new Exception(topBarNavigationException);
}
}
附言感谢您的格式编辑:)
【问题讨论】:
标签: c# selenium webdriver automated-tests