Selenium2 和 webdriver 的一个很好的工作示例

2022-01-16 00:00:00 selenium-webdriver webdriver java

我一直在使用 selenium 1,但现在想迁移到 selenium2/webdriver.老实说,我觉得从 selenium2/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");
    }
}

现在,用户登录后,会重定向到不同的页面.据我了解,我现在应该创建一个代表当前页面的新页面对象......事实是我不知道如何?我在哪里可以找到一些超越hello world"级别的优秀工作示例?我应该如何继续这个例子?

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?

提前致谢!

推荐答案

这些网站都给出了一些例子:

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

这个页面给出了一些关于使用 PageFactory 来支持页面对象的细节:http://code.google.com/p/selenium/wiki/PageFactory

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;     
  }
} 

并更改 loginAs 以返回一个表示浏览器在登录后导航到的页面的类:

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

相关文章