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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16508604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:12:43  来源:igfitidea点击:

How to use @FindBy annotation in Selenium WebDriver

javaselenium-webdriverannotationstestngfindby

提问by Diego Macario

I want to know what wrong with my code, because when I try to test my code, I didn′t get anything.

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

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();

}

}

}

I′m using Selenium WebDriverand TestNG, and I tried to test some entries in JSFpage.

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

采纳答案by e1che

There's a difinition for @BeforeClass :

@BeforeClass 有一个定义:

@BeforeClass
Run before all the tests in a class

And @FindByis "executed" each time that you'll call the class.

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

Actually your @FindByis called before the @BeforeClassso it won't work.

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

What i can suggest to you is to keep the @FindBybut let's start to use the PageObject pattern.

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

You keep your test's page and you create another class for your objects like :

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

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
} 

Your SeleniumTest'll looks like that :

你的 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

If you're going to use this tell me what's up.

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