A good working example of Selenium2 and webdriver

前端 未结 2 1620
南笙
南笙 2020-12-16 00:05

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\

相关标签:
2条回答
  • 2020-12-16 00:48

    This question is pretty old, but I thought it might still be worth sharing.

    Generally, I'll first create the required page object classes. Then I create a separate class for the test logic, where you would put your 'user workflow' of clicks and other page interactions. From the sample code provided, I'm assuming that this class would replace main(). This is also the class where I include things like testNG/junit, test annotations, and dataProviders (not strictly required, but if you use those things, that may be helpful to note) In this class, you can instantiate the classes for the pages you will interact with as you need them since the webdriver object you created controls the browser, not the page classes.

    Doing things this way allows for simple changes to test workflows, and also to the page objects in case the actual pages are changed, or you just have new test requirements.

    My favorite side effect of this method is that the class with the workflow can be a very readable 'script' of the test with all of the ugly details in the actual tests hidden under calls like loginPage.Login() and loginPage.LoginSucceeded() so a casual pass doesn't see the details of user credential lookups, handling 404's/400's, finding and clicking the login button, etc.

    0 讨论(0)
  • 2020-12-16 00:57

    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);                   
    }
    
    0 讨论(0)
提交回复
热议问题