我試圖檢查頁面上是否存在具有給定類的DIV
。測試團隊使用的模式是查找元素,說明期望的結果,然後執行一個簡單的if-else,如下所示(只是爲了解釋下面的佈局)。WebDriver C# - IWebElement和字符串之間的平等檢查
如果我從var topNavClassName assignment
的末尾刪除.ToString()
,在if
聲明平等檢查報告Operator '=='
不能應用於IWebElement and string
類型的操作數。
但保持這和運行代碼時,寫入線回來爲: 錯誤:
I expected to find the main navigation Div of 'container-fluid', but instead I got 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);
}
}
編輯:作爲一個說明我試圖改變,如果(topNavClassName == expectedTopNavClassName)
到如果(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);
}
}
P.S.感謝格式編輯:)