2013-12-05 1 views
0

У меня есть код ниже. Я хочу повторно использовать функции в другом java-файле. Как это сделать с помощью объектов страницы?Как использовать объекты страницы в селене

public class LoginPage { 


     private final WebDriver driver; 

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

      // Check that we're on the right page. 
      if (!"Outreach Configuration".equals(driver.getTitle())) { 
       // Alternatively, we could navigate to the login page, perhaps logging out first 
       throw new IllegalStateException("This is not the login page"); 
      } 
     } 

     // The login page contains several HTML elements that will be represented as WebElements. 
     // The locators for these elements should only be defined once. 

     // By usernameLocator = By.name("username"); 
     // By passwordLocator = By.name("password"); 
      By loginButtonLocator = By.name("submit"); 

     // The login page allows the user to type their username into the username field 
     public LoginPage typeUsername(String username) { 
      // This is the only place that "knows" how to enter a username 
      driver.findElement(By.name("username")).sendKeys(username); 

      // Return the current page object as this action doesn't navigate to a page represented by another PageObject 
      return this;  
     } 

     // The login page allows the user to type their password into the password field 
     public LoginPage typePassword(String password) { 
      // This is the only place that "knows" how to enter a password 
      //driver.findElement(passwordLocator).sendKeys(password); 
      driver.findElement(By.name("password")).sendKeys(password); 
      // Return the current page object as this action doesn't navigate to a page represented by another PageObject 
      return this;  
     } 

     // The login page allows the user to submit the login form 
     public HomePage submitLogin() { 
      // This is the only place that submits the login form and expects the destination to be the home page. 
      // A seperate method should be created for the instance of clicking login whilst expecting a login failure. 
      driver.findElement(By.name("submit")).submit(); 

      // Return a new page object representing the destination. Should the login page ever 
      // go somewhere else (for example, a legal disclaimer) then changing the method signature 
      // for this method will mean that all tests that rely on this behaviour won't compile. 
      return new HomePage(driver);  
     } 

     // The login page allows the user to submit the login form knowing that an invalid username and/or password were entered 
     public LoginPage submitLoginExpectingFailure() { 
      // This is the only place that submits the login form and expects the destination to be the login page due to login failure. 
     // driver.findElement(By.name("submit")).submit(); 

      // Return a new page object representing the destination. Should the user ever be navigated to the home page after submiting a login with credentials 
      // expected to fail login, the script will fail when it attempts to instantiate the LoginPage PageObject. 
      return new LoginPage(driver); 
     } 

     // Conceptually, the login page offers the user the service of being able to "log into" 
     // the application using a user name and password. 
     public HomePage loginAs(String username, String password) { 
      // The PageObject methods that enter username, password & submit login have already defined and should not be repeated here. 
      typeUsername(username); 
      typePassword(password); 
      return submitLogin(); 
     } 
     public static void main(String[] args) { 
      WebDriver driver = new FirefoxDriver(); 

      // And now use this to visit Google 
      driver.get(""); 
      LoginPage login = new LoginPage(driver); 
      try { 
       Thread.sleep(5000); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      HomePage a=login.loginAs("username","password"); 
      System.out.println(a); 
      //driver.findElement(By.className("newbutton")).click(); 


     } 
    } 

ответ

0

Метод main() не должен быть частью страницы объекта, просто переместить его в его собственном классе. LoginPage уже следует шаблону объекта страницы и может быть использован повторно, если требуется, например, в другом основном методе или другом классе.

В самом простом случае классы объектов страницы и класс, содержащий логику выполнения, должны быть частью одного и того же пакета Java и пространства имен, чтобы иметь возможность «видеть» друг друга. Кроме того, вы можете также иметь объекты страницы в другом пакете и использовать import.

package testing; 

public class LoginPage { 
    //all your your code minus the main method 
} 

public class LoginTest { 
    public static void main(String[] args) { 
    //your main method logic here 

    } 
} 

public class AnotherLoginTest { 
    public static void main(String[] args) { 
    //you can reuse the LoginPage here and try login with another set of credentials. 

    } 
} 

Примечание: Я не проверял ли ваши шаги для входа на самом деле являются правильными (не в рамках вопроса) - вы должны правильно ориентироваться на правильный URL, а затем выполнить свои шаги.

+0

как я могу вызвать методы из LoginPage в другом java-файле? – Jay

0

Вам не нужно возвращать объект страницы в своих методах, который вы назвали «typeUsername» и «typePassword». Вам нужно вернуть объект страницы только для событий, которые изменяют DOM/страницу.

+0

Да, не нужно. Тем не менее, это полезно, когда цепочки действий, таких как 'login.typeUsername (name) .typePassword (pwd) .submitLogin()' – Faiz

+0

Если fluent-api - это то, что вы хотите, я бы сделал это по-другому. Вы можете создать внутренний класс с методами, которые «возвращают это»; а затем создайте его следующим образом: login.goFluent(). typePassword (x) .submitLogin(). verify() и т. д. Я делаю это так, чтобы мои объекты страницы могли работать либо свободно, либо регулярно. – djangofan

Смежные вопросы