【问题标题】:Why should I use @FindBy instead of driver.findElement () in Page Object Class为什么我应该在页面对象类中使用@findby而不是driver.findElement()
【发布时间】:2019-02-04 01:20:51
【问题描述】:

我正在创建一个页面对象框架,同时通过它的概念,我知道页面工厂(@FindBy)与页面对象一起使用。 但是,当我可以在 Page Object 类中将 driver.findElement 与我的定位器一起使用时,我无法理解为什么需要使用 @FindBy。例如:

//带有@FindBy 的代码

  public class LoginPage{

      public LoginPage(WebDriver driver)){
      PageFactory.initElements(driver,this);
     }

     public WebElement q;

    }

    public class TestCase{

WebDriver driver=new FirefoxDriver();
LoginPage logPage=new LoginPage(driver);

 public void enterUserName(){
   logPage.q.sendKeys("username");

}
}

//带有 driver.findElement 的代码

public class LoginPage{

 public WebElement q=driver.findElement(By.id('q'));

}

public class TestCase{
WebDriver driver=new FirefoxDriver();
 LoginPage logPage=new LoginPage();

 public void enterUsername(){
  logPage.q.sendKeys("username");
}

}

这两个代码之间有什么区别,因为这两个代码本质上都在做同样的事情?

【问题讨论】:

标签: selenium-webdriver pageobjects page-factory


【解决方案1】:

从根本上说,无论您使用的是 Driver.FindElement() 还是 @FindBy 注释,在测试的运行方式和驱动程序正在做什么方面可能并没有太大的区别。在我看来,使用@FindBy 的“好处”是它指导您将所有与特定页面相关的 WebElements 和方法保存在一个位置,并将页面元素的查找与您携带的方法分开在页面上,例如请参阅下面的简要示例登录页面(在 C# 中):

public class LoginPage
{
    public IWebDriver Driver;

    [FindsBy(How = How.Id, Using = "username")]
    public IWebElement UsernameField;

    [FindsBy(How = How.Id, Using = "password")]
    public IWebElement PasswordField;

    [FindsBy(How = How.Id, Using = "submit")]
    public IWebElement SubmitButton;

    public LoginPage(IWebDriver driver)
    {
        Driver = driver;
        PageFactory.InitElements(this, new RetryingElementLocator(Driver, TimeSpan.FromSeconds(10)));
    }

    // By this point, all your elements on the page are declared and located,
    // you're now free to carry out whatever operations you'd like on the page 
    // without having to make any further declarations

    public void Login(string username, string password)
    {
        UsernameField.SendKeys(username);
        PasswordField.SendKeys(password);
        SubmitButton.Click();
    }
}

所以,我会说这主要是偏好,但我也认为@FindBy 注释带来的“整洁”/组织有一些令人信服的论据。

【讨论】:

    猜你喜欢
    • 2015-01-08
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 2015-08-08
    • 2013-06-07
    • 2011-06-19
    • 2013-08-28
    • 2018-05-10
    相关资源
    最近更新 更多