Assume that we are using Page object model. Page Object class:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPage {
@FindBy(id="loginInput") //method used to find WebElement, in that case Id
WebElement loginTextbox;
@FindBy(id="passwordInput")
WebElement passwordTextBox;
//xpath example:
@FindBy(xpath="//form[@id='loginForm']/button(contains(., 'Login')")
WebElement loginButton;
public void login(String username, String password){
// login method prepared according to Page Object Pattern
loginTextbox.sendKeys(username);
passwordTextBox.sendKeys(password);
loginButton.click();
// because WebElements were declared with @FindBy, we can use them without
// driver.find() method
}
}
And Tests class:
class Tests{
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
LoginPage loginPage = new LoginPage();
//PageFactory is used to find elements with @FindBy specified
PageFactory.initElements(driver, loginPage);
loginPage.login("user", "pass");
}
}
There are few methods to find WebElements using @FindBy - check Syntax section.