2010-10-20 12 views
11

Mi piace molto il modo in cui il selenio 2 per convenzione ti spinge ad usare PageObjects come POJOs e quindi semplicemente usando PageFactory per istanziare i campi di questa classe.Oggetto selenio Riutilizzo degli oggetti

Quello che sto trovando limitante è che riutilizziamo molti elementi su molte pagine diverse. Il grosso problema è che questi componenti riutilizzati non hanno lo stesso id/nome quando appaiono su pagine diverse; tuttavia i test che eseguiremo per ciascuno di essi sono gli stessi.

Ad esempio, raccogliamo le date in molti posti. Quindi un oggetto ad esempio la pagina di questo potrebbe essere (mese, giorno campi rimossi):

public class DatePageObject { 
    private WebDriver driver; 

    DatePageObject(WebDriver driver) { 
     this.driver = driver; 
    } 

    @FindBy(id = "someIdForThisInstance") 
    private WebElement year; 

    public void testYearNumeric() { 
     this.year.sendKeys('aa'); 
     this.year.submit(); 
     //Logic to determine Error message shows up 
    } 
} 

Poi ho potuto semplicemente testare questo con il codice qui sotto:

public class Test { 
    public static void main(String[] args) { 
     WebDriver driver = new FirefoxDriver(); 
     DatePageObject dpo = PageFactory.initElements(driver, DriverPageObject.class); 
     driver.get("Some URL"); 
     dpo.testYearNumeric(); 
    } 
} 

Quello che mi piacerebbe davvero fare è una configurazione in cui con Spring posso iniettare quell'id/name/xpath, ecc ... nell'applicazione.

C'è un modo per farlo, senza perdere la possibilità di utilizzare PageFactory?

Modifica 1 - Aggiunta di classi di livello base ideali, lavorando su localizzatori personalizzati e fabbriche.

public class PageElement { 
    private WebElement element; 
    private How how; 
    private String using; 

    PageElement(How how, String using) { 
     this.how = how; 
     this.using = using; 
    } 
    //Getters and Setters 
} 


public class PageWidget { 
    private List<PageElement> widgetElements; 
} 


public class Screen { 
    private List<PageWidget> fullPage; 
    private WebDriver driver; 

    public Screen(WebDriver driver) { 
     this.driver = driver; 
     for (PageWidget pw : fullPage) { 
      CustomPageFactory.initElements(driver, pw.class); 
     } 
} 

Edit 2 - Proprio come una nota, a patto che si esegue selenio 2.0.a5 o superiore, è ora possibile dare al conducente un valore di timeout implicita.

Quindi è possibile sostituire il codice con:

private class CustomElementLocator implements ElementLocator { 
    private WebDriver driver; 
    private int timeOutInSeconds; 
    private final By by; 


    public CustomElementLocator(WebDriver driver, Field field, 
      int timeOutInSeconds) { 
     this.driver = driver; 
     this.timeOutInSeconds = timeOutInSeconds; 
     CustomAnnotations annotations = new CustomAnnotations(field); 
     this.by = annotations.buildBy(); 
     driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); //Set this value in a more realistic place 
    } 


    public WebElement findElement() { 
     return driver.findElement(by); 
    } 
} 

risposta

15

È possibile costruire la vostra pagina Oggetto del Web Elements comune (appena inventato questo nome :)) - ogni CWE rappresenterà un "widget" che viene utilizzato su diverse pagine. Nel tuo esempio questa sarà una sorta di Date Widget - contiene l'anno, il mese e un giorno. Fondamentalmente sarà un oggetto Page.

PageFactory richiede le costanti di stringa da utilizzare nelle annotazioni @FindBy.

Per risolvere questa limitazione abbiamo creato il nostro ElementLocator s.

È possibile utilizzare il DateWidget nel test:

.... 
DateWidget widget = new DateWidget(driver, "yearId", "monthId", "dayId"); 
.... 

public void testYearNumeric() { 
     widget.setYear("aa"); 
     widget.submit(); 
     //Logic to determine Error message shows up 

     // ... and day 
     widget.setDay("bb"); 
     widget.submit(); 
     //Logic to determine Error message shows up 
    } 

La classe DateWidget, che contiene localizzatori personalizzati e parser di annotazione è:

package pagefactory.test; 

import java.lang.reflect.Field; 

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.support.FindBy; 
import org.openqa.selenium.support.PageFactory; 
import org.openqa.selenium.support.pagefactory.Annotations; 
import org.openqa.selenium.support.pagefactory.ElementLocator; 
import org.openqa.selenium.support.pagefactory.ElementLocatorFactory; 
import org.openqa.selenium.support.ui.ExpectedCondition; 
import org.openqa.selenium.support.ui.Wait; 
import org.openqa.selenium.support.ui.WebDriverWait; 

public class DateWidget { 

    // These constants are used to identify that they should be changed to the actual IDs 
    private static final String YEAR_ID = "$YEAR_ID$"; 
    private static final String MONTH_ID = "$MONTH_ID$"; 
    private static final String DAY_ID = "$DAY_ID$"; 

    // Elements whose ids will be replaced during run-time 
    /** Year element */ 
    @FindBy(id = YEAR_ID) 
    private WebElement year; 

    /** Month element */ 
    @FindBy(id = MONTH_ID) 
    private WebElement month; 

    /** day element */ 
    @FindBy(id = DAY_ID) 
    private WebElement day; 

    // The ids of the elements 
    /** ID of the year element */ 
    private String yearId; 

    /** ID of the month element */ 
    private String monthId; 

    /** ID of the day element */ 
    private String dayId; 

    public DateWidget(WebDriver driver, String yearId, String monthId, 
      String dayId) { 
     this.yearId = yearId; 
     this.monthId = monthId; 
     this.dayId = dayId; 

     PageFactory.initElements(new CustomLocatorFactory(driver, 15), this); 
    } 

    public String getYear() { 
     return year.getValue(); 
    } 

    public void setYear(String year) { 
     setValue(this.year, year); 
    } 

    public String getMonth() { 
     return month.getValue(); 
    } 

    public void setMonth(String month) { 
     setValue(this.month, month); 
    } 

    public String getDay() { 
     return day.getValue(); 
    } 

    public void setDay(String day) { 
     setValue(this.day, day); 
    } 

    public void submit() { 
     year.submit(); 
    } 

    private void setValue(WebElement field, String value) { 
     field.clear(); 
     field.sendKeys(value); 
    } 

    private class CustomLocatorFactory implements ElementLocatorFactory { 
     private final int timeOutInSeconds; 
     private WebDriver driver; 

     public CustomLocatorFactory(WebDriver driver, int timeOutInSeconds) { 
      this.driver = driver; 
      this.timeOutInSeconds = timeOutInSeconds; 
     } 

     public ElementLocator createLocator(Field field) { 
      return new CustomElementLocator(driver, field, timeOutInSeconds); 
     } 
    } 

    private class CustomElementLocator implements ElementLocator { 
     private WebDriver driver; 
     private int timeOutInSeconds; 
     private final By by; 

     public CustomElementLocator(WebDriver driver, Field field, 
       int timeOutInSeconds) { 
      this.driver = driver; 
      this.timeOutInSeconds = timeOutInSeconds; 
      CustomAnnotations annotations = new CustomAnnotations(field); 
      this.by = annotations.buildBy(); 
     } 

     @Override 
     public WebElement findElement() { 
      ExpectedCondition<Boolean> e = new ExpectedCondition<Boolean>() { 
       public Boolean apply(WebDriver d) { 
        d.findElement(by); 
        return Boolean.TRUE; 
       } 
      }; 
      Wait<WebDriver> w = new WebDriverWait(driver, timeOutInSeconds); 
      w.until(e); 

      return driver.findElement(by); 
     } 
    } 

    private class CustomAnnotations extends Annotations { 

     public CustomAnnotations(Field field) { 
      super(field); 
     } 

     @Override 
     protected By buildByFromShortFindBy(FindBy findBy) { 

      if (!"".equals(findBy.id())) { 
       String id = findBy.id(); 
       if (id.contains(YEAR_ID)) { 
        id = id.replace(YEAR_ID, yearId); 
        return By.id(id); 
       } else if (id.contains(MONTH_ID)) { 
        id = id.replace(MONTH_ID, monthId); 
        return By.id(id); 
       } else if (id.contains(DAY_ID)) { 
        id = id.replace(DAY_ID, dayId); 
        return By.id(id); 
       } 
      } 

      return super.buildByFromShortFindBy(findBy); 
     } 

    } 

} 
+0

Questo ha sicuramente mi ha ottenuto sulla pista corretta. Speravo di estenderlo ulteriormente oltre ai soli ID (potevi iniettare ogni mezzo necessario e quindi individuare). Il mio problema era che non stavo vedendo come venivano creati quei Field, il che mi stava impedendo di afferrare correttamente l'ElementLocator. – Scott

Problemi correlati