发送到函数后,IWebElement变为null

时间:2017-07-18 14:39:36

标签: c# selenium

我想检查是否显示了IWebElement。当我尝试联系并查看课程中的IWebElement时,一切正常,但当我将其发送到我的KontrolElement()函数时,我会得到NullReferenceExceptionKontrolElemet()是必需的,因为此过程会多次发生。

KontrolElement()

//This is inside a class called 'Helpers'
public void KontrolElement(IWebDriver WebDriver, IWebElement WebElement, string msg)
{
    try
    {
        //"WebElement" is null
        Assert.IsTrue(WebElement.Displayed);
    }
    catch (AssertionException)
    {
        Console.WriteLine("Kontrol: " + msg);

        //Sends an E-mail with the screenshot of the page attached to it
        new ScreenShot().Crush(WebDriver, msg, "");
    }
}

我如何使用它(' el'通常是IReadOnlyCollection中的一个对象,它是带有foreach循环的迭代):

//This takes place in the PageObject class which extends 'Helpers'
IWebElement el = WebDriver.FindElement(By.ClassName("listTop"));

//Console.WriteLine(el.Displayed) outputs True

KontrolElement(WebDriver, el, "el is not displayed");

有没有人遇到这样的问题?什么是替代解决方案?

2 个答案:

答案 0 :(得分:0)

我不喜欢将Assert包裹起来或将任何简单包装到函数中。你有什么收获?不要让事情变得比他们需要的更复杂。

删除该功能,只需在脚本中使用以下代码

IWebElement el = WebDriver.FindElement(By.ClassName("listTop"));
Assert.IsTrue(el.Displayed, "Verify element is displayed");

我会将断言评论中的“元素”更改为更具体的内容,例如“显示验证登录按钮”。

如果您坚持使用此功能,为什么在不使用时传递IWebDriver

另一件事......抓住通用Exception并不是一个好习惯。只抓住你打算处理的东西。

答案 1 :(得分:0)

System.DebugNlog库之间的冲突导致了问题,编译器会在Assert库中看到System.Debug引用,而这个引用会引发NullReferenceException库{1}}。