> Markdown version of [E2E Testing with Selenium](https://vaadin.com/docs/latest/it/flow/testing/selenium). Section index: [llms.txt](https://vaadin.com/docs/latest/it/flow/llms.txt)

# End-to-End Testing con 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](https://vaadin.com/docs/latest/it/flow/testing.md#e2e-tools).

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.

## <a id="configurazione-di-selenium"></a>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.

`pom.xml`

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

In un progetto generato da [Vaadin Start](https://start.vaadin.com/), la versione di Selenium è già gestita, quindi Lei può omettere il numero di versione. Lei può trovare l’ultima versione di Selenium [qui](https://search.maven.org/artifact/org.seleniumhq.selenium/selenium-java).

Da Selenium 4.6, un [Selenium Manager](https://www.selenium.dev/documentation/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.

## <a id="crei-il-suo-primo-test-selenium"></a>Crei il Suo primo test Selenium

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

`SimpleIT.java`

```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](https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/WebDriverWait.html) 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.

## <a id="esecuzione-dei-test"></a>Esecuzione dei test

Se Lei ha aggiunto i Suoi test Selenium a un progetto generato da [Vaadin Start](https://start.vaadin.com/), può eseguirli eseguendo il seguente comando dal terminale:

```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:

`pom.xml`

```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](https://github.com/vaadin/skeleton-starter-flow) e un [progetto CDI](https://github.com/vaadin/skeleton-starter-flow-cdi).

## <a id="ricerca-e-interazione-con-gli-elementi"></a>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.

`SimpleIT.java`

```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`](https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/By.html).

2. Chiami `click()` per cliccare sul [`WebElement`](https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/WebElement.html).

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.

## <a id="test-selenium-avanzato"></a>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](https://start.vaadin.com/).

`SimpleIT.java`

```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](https://developer.mozilla.org/en-US/docs/Web/XPath) per trovare l’elemento. Lo `xpath` può essere generato dal [Selenium IDE](https://www.selenium.dev/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](https://www.selenium.dev/documentation/webdriver/elements/) ufficiale.

## <a id="estensione-selenium-jupiter"></a>Estensione Selenium-Jupiter

[Selenium-Jupiter](https://bonigarcia.dev/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:

```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`
