Java – a good working example of selenium 2 and webdriver

I've been using selenium 1, but now I want to migrate to selenium 2 / webriver To be honest, I find it a little difficult to start with selenium 2 / webriver In essence, I don't know how to work between page objects Here is my example:

public class LoginPage {
    private final WebDriver driver;

    public LoginPage(WebDriver driver) {
        this.driver = driver; 
    }

    public void loginAs(String username,String password) {
        driver.get("http://url_to_my_webapp");        
        driver.findElement(By.id("username")).sendKeys(username);
        driver.findElement(By.id("pwd")).sendKeys(password);
        driver.findElement(By.className("button")).submit();                  
    }

    public static void main(String[] args){
        LoginPage login = new LoginPage(new FirefoxDriver());
        login.loginAs("user","pass");
    }
}

Now, after the user logs in, redirection to a different page occurs As far as I know, I should now create a new page object representing the current page... In fact, I don't know how? Where can I find some good examples beyond the "Hello world" level? How can I continue this example?

Thank you in advance!

Solution

These websites provide some examples:

Step-by-step selenium tests with page objects, dsl and fun!

http://www.wakaleo.com/blog/selenium-2-web-driver-the-land-where-page-objects-are-king

This page provides some details of using pagefactory to support page objects: http://code.google.com/p/selenium/wiki/PageFactory

You can extend your example to handle page objects by creating a class for each page, for example:

public class MainPage 
{ 
  private final WebDriver driver;  

  public MainPage(WebDriver driver) 
  {     
    this.driver = driver;  
  }   

  public void doSomething() 
  {      
    driver.findElement(By.id("something")).Click;     
  }
}

And change loginas to return a class representing the page browsed by the browser after login:

public MainPage loginAs(String username,String password) 
{       
    driver.get("http://url_to_my_webapp");             
    driver.findElement(By.id("username")).sendKeys(username);     
    driver.findElement(By.id("pwd")).sendKeys(password);     
    driver.findElement(By.className("button")).submit();
    // Add some error checking here for login failure
    return new MainPage(driver);                   
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>