Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

java - A good working example of Selenium2 and webdriver

I've been using selenium 1, but now want to migrate to selenium2/webdriver. To be honest, I find a little bit difficult to start with selenium2/webdriver. 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 user is logged in, a redirection to different page occurs. As far as I understand, I should now make a new page object that represents current page... The fact is I don't know how? Where can I find some good working examples which are going beyond "hello world" level? How should I continue this example?

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

These sites both give some examples:

http://luizfar.wordpress.com/2010/09/29/page-objects/

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

This page gives some details on using PageFactory to support page objects: http://code.google.com/p/selenium/wiki/PageFactory

You could extend your example to work with page objects by creating a class for each page, e.g.:

public class MainPage 
{ 
  private final WebDriver driver;  

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

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

and changing loginAs to return a class that represents the page that the browser navigates to 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);                   
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...