【问题标题】:How to use @FindBy annotation in Selenium WebDriver如何在 Selenium WebDriver 中使用 @FindBy 注释
【发布时间】:2013-05-06 16:38:08
【问题描述】:

我想知道我的代码出了什么问题,因为当我尝试测试我的代码时,我什么也没得到。

public class SeleniumTest {

private WebDriver driver;
private String nome;
private String idade;

@FindBy(id = "j_idt5:nome")
private WebElement inputNome;

@FindBy(id = "j_idt5:idade")
private WebElement inputIdade;

@BeforeClass
public void criarDriver() throws InterruptedException {

    driver = new FirefoxDriver();
    driver.get("http://localhost:8080/SeleniumWeb/index.xhtml");
    PageFactory.initElements(driver, this);

}

@Test(priority = 0)
public void digitarTexto() {

    inputNome.sendKeys("Diego");
    inputIdade.sendKeys("29");

}

@Test(priority = 1)
public void verificaPreenchimento() {

    nome = inputNome.getAttribute("value");
    assertTrue(nome.length() > 0);

    idade = inputIdade.getAttribute("value");
    assertTrue(idade.length() > 0);
}

@AfterClass
public void fecharDriver() {

    driver.close();

}

}

我正在使用Selenium WebDriverTestNG,并尝试测试JSF 页面中的一些条目。

【问题讨论】:

  • 你得到的输出是什么?
  • 代码没问题,它按预期对我有用。你确定你的http://localhost:8080/SeleniumWeb/index.xhtml 没问题?

标签: java selenium-webdriver annotations testng findby


【解决方案1】:

@BeforeClass 有一个定义:

@BeforeClass
Run before all the tests in a class

@FindBy 每次调用该类时都会“执行”。

实际上你的@FindBy@BeforeClass 之前被调用所以它不会工作。

我可以建议您保留@FindBy,但让我们开始使用PageObject pattern.

您保留测试页面并为您的对象创建另一个类,例如:

public class PageObject{
  @FindBy(id = "j_idt5:nome")
  private WebElement inputNome;

  @FindBy(id = "j_idt5:idade")
  private WebElement inputIdade;

  // getters
  public WebElement getInputNome(){
    return inputNome;
  }

  public WebElement getInputIdade(){
    return inputIdade;
  }

  // add some tools for your objects like wait etc
} 

你的 SeleniumTest 看起来像这样:

@Page
PageObject testpage;

@Test(priority = 0)
public void digitarTexto() {

  WebElement inputNome = testpage.getInputNome();
  WebElement inputIdade = testpage.getInputIdade();

  inputNome.sendKeys("Diego");
  inputIdade.sendKeys("29");
}
// etc

如果你要使用这个,告诉我发生了什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多