用户代码未处理Selenium C#SendKeys NullreferenceException

时间:2019-04-19 21:08:28

标签: c# selenium selenium-webdriver specflow

我在使用SendKeys将一些文本输入文本字段时遇到问题。 我收到错误消息:

NullreferenceException was unhandled by user code
An exception of type 'System.NullReferenceException' occurred in companyautomation.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

在调试期间,我发现Input字段为null。我不知道为什么元素为空,定位器似乎没有用。这是定位器的简单ID。 我已经检查了用于检查元素的定位器的CSS,它是正确的。

错误所在的行,用户名字段元素为空

UsernameField.SendKeys(Username);

我的代码段是:

public class LoginPage : BasePage
{

    public LoginPage(IWebDriver Browser) : base(Browser)
    {            
    }

    public void EnterUsername(string Username)
    {
        UsernameField.SendKeys(Username);
    }

    [FindsBy(How = How.CssSelector, Using = "#LoginUsername")]
    private IWebElement UsernameField { get; set; }        
}

public class BasePage : DriverClass
{        
    protected IWebDriver Driver { get; set; }

    public BasePage(IWebDriver driver)
    {
        Driver = driver;
        PageFactory.InitElements(Driver, this);
    }

    //** All Page Objects **//
    #region Page Objects

    private LoginPage LoginPage => new LoginPage(Driver);
    private Browsers Browser => new Browsers();

    #endregion    
} 

[Binding, Parallelizable]
[Scope(Tag = "Login")]
public class LoginSteps : BasePage
{
    public LoginSteps(IWebDriver driver) : base(driver)
    {
    }

    [Given(@"I login with (.*) with password (.*)")]
    public void GivenILoginWith_Valid_UserWithPassword(string Username, string Password)
    {
        LoginPage.EnterUsername(Username);
        LoginPage.EnterUserPassword(Password);            
    }

HTML:

<input value=""
       data-val="true"
       data-val-required="Please enter a valid username"
       id="LoginUsername"
       name="LoginUsername"
       ng-blur="vm.analytics.push({ 'category' : 'Login' , 'action' : 'Left Username field', 'label' : 'Language: en'})"
       ng-focus="vm.analytics.push({ 'category' : 'Login' , 'action' : 'Enter Username field', 'label' : 'Language: en'})"
       placeholder="Username"
       title="Username"
       type="text">

0 个答案:

没有答案