如何在Selenium WebDriver中使用@FindBy注释

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

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页面中测试一些条目。

@BeforeClass有一个定义:

 @BeforeClass Run before all the tests in a class 

每次你打电话给@FindBy被“执行”。

实际上你的@FindBy@BeforeClass之前调用,所以它不起作用。

我可以建议你保留@FindBy但让我们开始使用PageObject模式。

保留测试页面,然后为对象创建另一个类,如:

 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 

如果你打算用这个告诉我发生了什么事。