Docs

Documentation versions (currently viewingVaadin 25)
Documentation translations (currently viewing)

Questa pagina è stata tradotta automaticamente dalla documentazione ufficiale, che si trova in https://vaadin.com/docs. Potrebbe contenere errori, inesattezze, o affermazioni errate. Vaadin non garantisce né rilascia alcuna dichiarazione in merito all’accuratezza, affidabilità, o tempestività della traduzione.

End-to-End Testing con Selenium

Descrive come configurare l’end-to-end testing per un’applicazione Vaadin usando Selenium.

Selenium è una popolare libreria open source per l’automazione del browser che viene spesso usata per automatizzare il testing delle applicazioni web, e Lei può usarla per testare le applicazioni Vaadin. Per come si confronta con TestBench e Playwright, veda Scelta di uno strumento di End-to-End Testing.

Questa guida descrive:

  • Come configurare Selenium;

  • La creazione di un semplice test Selenium;

  • Le basi per trovare e interagire con gli elementi in un test Selenium; e

  • Come può essere creato un test Selenium più complesso.

Configurazione di Selenium

Per usare Selenium in un’applicazione Vaadin, Lei deve eseguire alcuni passaggi. Per prima cosa, aggiunga la dipendenza della libreria Selenium al file pom.xml del Suo progetto.

Source code
pom.xml
<!-- Selenium Library -->
<dependency>
   <groupId>org.seleniumhq.selenium</groupId>
   <artifactId>selenium-java</artifactId>
</dependency>

In un progetto generato da Vaadin Start, la versione di Selenium è già gestita, quindi Lei può omettere il numero di versione. Lei può trovare l’ultima versione di Selenium qui.

Da Selenium 4.6, un Selenium Manager integrato scarica e gestisce automaticamente i driver del browser. Non è necessario installare o configurare i driver manualmente — l’istanziazione di un driver come ChromeDriver si occupa di tutto.

Crei il Suo primo test Selenium

Come esempio, il seguente frammento di codice verifica se il testo del Button caricato corrisponde a "Say Hello".

Source code
SimpleIT.java
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;

import static java.time.Duration.ofSeconds;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;

public class SimpleIT {

    @Test
    public void checkPageLoad() {
        var driver = new ChromeDriver(); 1

        try { 2
            driver.get("http://localhost:8080/hello"); 3

            new WebDriverWait(driver, ofSeconds(30), ofSeconds(1))
                    .until(titleIs("Hello World")); 4

            var button = driver.findElement(By.xpath("//vaadin-button[contains(.,'Say hello')]")); 5

            assertEquals("Say hello", button.getText()); 6
        } finally {
            driver.quit(); 7
        }
    }
}
  1. Istanzia il ChromeDriver, che è usato per interagire con il browser web Chrome. Selenium Manager scarica automaticamente il driver richiesto.

  2. Racchiuda il test in un blocco try/finally in modo che la sessione si chiuda anche quando il test fallisce.

  3. Indirizzi il ChromeDriver a caricare l’URL.

  4. Poiché Flow produce un frontend single-page, Selenium non è consapevole della manipolazione del DOM dopo che la pagina iniziale è stata caricata. Lei può usare l’API WebDriverWait di Selenium per attendere finché il DOM non è stato compilato.

  5. Una volta che Lei è sicuro che il titolo della pagina sia disponibile, provi a recuperare un Button in questa pagina.

  6. Verifichi se il testo del Button è "Say Hello".

  7. Chiuda la sessione del browser dopo il test.

Esecuzione dei test

Se Lei ha aggiunto i Suoi test Selenium a un progetto generato da Vaadin Start, può eseguirli eseguendo il seguente comando dal terminale:

Source code
terminal
mvn verify -Pit

Questo esegue i test nel profilo it, che avvia il server Spring Boot prima che i test vengano eseguiti — e lo arresta successivamente. Se Lei esegue il test in questo modo, le classi di test devono terminare con IT.

Il seguente elenco mostra la parte del file pom.xml che è responsabile dell’avvio e dell’arresto del server Spring Boot:

Source code
pom.xml
<profile>
    <id>it</id>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>start-spring-boot</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>start</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>stop-spring-boot</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            ...

Per un progetto non Spring Boot, ci sono esempi su GitHub del profilo it per altri stack tecnologici, incluso per un progetto Java semplice e un progetto CDI.

Ricerca e interazione con gli elementi

Il seguente esempio dimostra un test che richiede di trovare e interagire con un elemento web. In particolare, trova il link alla pagina "About" e lo clicca. Questa azione, naturalmente, attiva la navigazione verso la pagina “About”. Il test poi attende finché la pagina "About" non è caricata e verifica che l’URL della pagina sia corretto.

Source code
SimpleIT.java
@Test
public void routeSwitch(){
  var driver = new ChromeDriver();

  try {
      //Loads the page
      driver.get("http://localhost:8080");

      //Have to explicitly wait because it takes time for compiled html to load
      new WebDriverWait(driver, ofSeconds(30), ofSeconds(1))
              .until(titleIs("Hello World"));

      driver.findElement(By.cssSelector("vcf-nav-item:nth-child(2)")) 1
              .click(); 2

      new WebDriverWait(driver, ofSeconds(30), ofSeconds(1))
              .until(titleIs("About")); 3

      var url = driver.getCurrentUrl(); 4

      //Checks whether the url matches
      assertEquals("http://localhost:8080/about", url);
  } finally {
      //Ends the browser session
      driver.quit();
  }
}
  1. Lei può trovare gli elementi usando il matcher By.

  2. Chiami click() per cliccare sul WebElement.

  3. Attenda prima il caricamento della pagina "About", prima di provare a ottenere l’URL. Questo riduce la flakiness.

  4. Usi il metodo comodo per ottenere l’URL corrente completo.

Test Selenium avanzato

Il seguente test dimostra come potrebbe apparire un test Selenium lungo. Questo test assume una vista master-detail del tipo che potrebbe essere generato da Vaadin Start.

Source code
SimpleIT.java
@Test
public void addUser(){
  var driver = new ChromeDriver();

  try {
      //Maximizes the screen
      driver.manage().window().maximize();

      //Loads the page
      driver.get("http://localhost:8080/master-detail");

      //Have to explicitly wait because it takes time for compiled html to load
      new WebDriverWait(driver, ofSeconds(30), ofSeconds(1))
              .until(titleIs("Master-Detail"));

      //Test data
      var firstName = "FirstName";
      var lastName = "LastName";
      var email = "first.last@example.com";
      var phone = "(111) 111-1111";
      //Cannot use simple String because the form and table display the dob differently
      var dob = LocalDate.of(2000, Month.JANUARY, 1);
      var occupation = "Forester";

      //Adds First Name
      var firstNameTextInput = driver.findElement(By.id("vaadin-text-field-0")); 1
      firstNameTextInput.click(); 2
      firstNameTextInput.sendKeys(firstName); 3

      //Adds Last Name
      var lastNameTextInput = driver.findElement(By.id("vaadin-text-field-1"));
      lastNameTextInput.click();
      lastNameTextInput.sendKeys(lastName);

      //Adds Email
      var emailTextInput = driver.findElement(By.id("vaadin-text-field-2"));
      emailTextInput.click();
      emailTextInput.sendKeys(email);

      //Adds Phone
      var phoneTextInput = driver.findElement(By.id("vaadin-text-field-3"));
      phoneTextInput.click();
      phoneTextInput.sendKeys(phone);

      //Adds DOB
      var dobTextInput = driver.findElement(By.id("vaadin-date-picker-4"));
      dobTextInput.click();
      dobTextInput.sendKeys(DateTimeFormatter.ofPattern("dd/MM/uuuu").format(dob));
      dobTextInput.sendKeys(Keys.ENTER); //Closes the pop-up Date Picker

      //Adds Occupation
      var occupationTextInput = driver.findElement(By.id("vaadin-text-field-5"));
      occupationTextInput.click();
      occupationTextInput.sendKeys(occupation);

      //Marks as Important
      driver.findElement(By.id("vaadin-checkbox-6"))
              .click();

      //Clicks Save
      driver.findElement(By.xpath("//vaadin-button[contains(.,'Save')]")).click(); 4

      //Sorts by Phone number so the sample user is visible on the screen
      driver.findElement(By.xpath("//vaadin-grid-sorter[contains(.,'Phone')]")).click();

      //Reduces verbosity
      var xPathStart = "//vaadin-grid-cell-content[contains(.,'";
      var xPathEnd = "')]";

      //Waits for the page to sort
      new WebDriverWait(driver, ofSeconds(30), ofSeconds(1))
              .until(visibilityOfElementLocated(By.xpath(xPathStart + firstName + xPathEnd)));

      //Gets the cells in the table for the newly added user
      var firstNameCell = driver.findElement(By.xpath(xPathStart + firstName + xPathEnd));
      var lastNameCell = driver.findElement(By.xpath(xPathStart + lastName + xPathEnd));
      var emailCell = driver.findElement(By.xpath(xPathStart + email + xPathEnd));
      var phoneCell = driver.findElement(By.xpath(xPathStart + phone + xPathEnd));
      var dobCell = driver.findElement(By.xpath(xPathStart + dob + xPathEnd));
      var occupationCell = driver.findElement(By.xpath(xPathStart + occupation + xPathEnd));

      //Assertions (5)
      assertEquals(firstName, firstNameCell.getText());
      assertEquals(lastName, lastNameCell.getText());
      assertEquals(email, emailCell.getText());
      assertEquals(phone, phoneCell.getText());
      assertEquals(dob.toString(), dobCell.getText());
      assertEquals(occupation, occupationCell.getText());
  } finally {
      //Ends the browser session
      driver.quit();
  }
}
  1. Lei può usare il matcher By.id() per trovare i campi con un id univoco. Lei può recuperare l’id usando l’inspector del Suo browser.

  2. Lei deve cliccare sul campo per simulare il comportamento reale di un utente finale.

  3. Lei può inviare pressioni di tasti usando il metodo sendKeys().

  4. Per gli elementi che non hanno un id, Lei può usare un xpath expression per trovare l’elemento. Lo xpath può essere generato dal Selenium IDE.

  5. Infine, verifichi se tutte le informazioni nelle celle della tabella corrispondono ai dati originali.

Per ulteriori scenari d’uso, veda la Selenium doc ufficiale.

Estensione Selenium-Jupiter

Selenium-Jupiter è un’estensione JUnit 5 che può essere usata per inizializzare, eseguire e gestire test basati sul browser.

La combinazione di TestBench con Selenium-Jupiter è mostrata nel seguente esempio:

Source code
Java
@ExtendWith(SeleniumJupiter.class)
public class SimpleCaseSeleniumIT implements HasElementQuery {

    private WebDriver driver;

    @BeforeEach
    public void beforeEach(ChromeDriver driver) {       // driver injection by Selenium-Jupiter
        this.driver = TestBench.createDriver(driver);   // TestBench driver proxy
        this.driver.get("https://" + IPAddress.findSiteLocalAddress() + ":8080");
    }

    @Test
    public void calculateOnePlusTwo() {
        $(ButtonElement.class).id("button_1").click();
        $(ButtonElement.class).id("button_+").click();
        $(ButtonElement.class).id("button_2").click();
        $(ButtonElement.class).id("button_=").click();
        Assertions.assertEquals("3.0",
                $(TextFieldElement.class).single().getValue());
    }

    @Override
    public SearchContext getContext() {
        return driver;
    }
}

D341245B-909F-455A-B78B-AC8CF58356C5