> Markdown version of [Getting Started](https://vaadin.com/docs/latest/it/flow/testing/end-to-end/getting-started). Section index: [llms.txt](https://vaadin.com/docs/latest/it/flow/llms.txt)

# Introduzione ai test end-to-end

È facile iniziare con i test end-to-end con Vaadin. Se desidera testare TestBench e vedere come vengono eseguiti i test, il modo più semplice è clonare il progetto di esempio su <https://github.com/vaadin/testbench-demo>. I test vengono eseguiti automaticamente sul suo Chrome locale quando esegue `mvn verify`.

## <a id="configurazione-del-progetto"></a>Configurazione del progetto

Per iniziare a usare TestBench in un progetto esistente, deve aggiungere la dipendenza TestBench (`com.vaadin`/`vaadin-testbench`) con scope `test`. Supponendo che abbia importato la Vaadin Bill-of-Materials (BOM) e che abbia un progetto Maven, tutto ciò che deve fare è aggiungere quanto segue:

**JUnit 4**

```xml
<dependency>
    <groupId>com.vaadin</groupId>
    <artifactId>vaadin-testbench</artifactId>
    <scope>test</scope>
</dependency>
<!-- Required for Vaadin 25+ with Spring Boot 4 (JUnit 6) -->
<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <scope>test</scope>
</dependency>
```

**JUnit 5/6 (JUnit 6 since Vaadin 25.0)**

```xml
<dependency>
    <groupId>com.vaadin</groupId>
    <artifactId>vaadin-testbench-junit6</artifactId> <!-- or vaadin-testbench-junit5 -->
    <scope>test</scope>
</dependency>
```

> **Note:** A partire da Vaadin 25 e Spring Boot 4, il framework di test predefinito è JUnit 6 (JUnit Platform). JUnit 6 mantiene la compatibilità API con JUnit 5, quindi `vaadin-testbench-junit5` e `vaadin-testbench-junit6` funzionano con entrambi, ma hanno dipendenze transitive di JUnit allineate alle rispettive versioni.
>
> Per i test JUnit 4 che usano `TestBenchTestCase`, la dipendenza `junit-vintage-engine` è necessaria perché JUnit 6 non esegue nativamente i test JUnit 4. Senza di essa, i test non verranno rilevati o eseguiti.

Lo scope `test` e il numero di versione sono predefiniti dalla Vaadin BOM.

Per poter eseguire i test in locale, potrebbe essere necessario installare un WebDriver per il suo browser. Veda [Installing WebDrivers](https://vaadin.com/docs/latest/it/flow/testing/end-to-end/installing-webdrivers.md) per maggiori dettagli.

## <a id="creazione-di-un-test-semplice"></a>Creazione di un test semplice

Esistono alcune parti fondamentali di qualsiasi test TestBench. Di seguito sono riportati i passaggi da seguire:

- Creare un’istanza del driver del browser per il browser che desidera usare. Per impostazione predefinita, TestBench usa il driver del browser Chrome.

- Aprire l’URL che contiene l’applicazione che desidera testare.

- Eseguire la logica di test e verificare che il risultato sia quello atteso.

- Chiudere l’istanza del driver per chiudere il browser.

Il seguente esempio di test esegue tutte le attività sopra indicate, con una logica di test che consiste nel fare clic sull’unico pulsante nella pagina e verificare che il testo del pulsante cambi quando viene cliccato. Se aggiunge questo test alla sua applicazione personalizzata, fallisce a meno che non lo modifichi.

Nel mondo Maven, tutte le classi di test si trovano nella directory `src/test/java`. Crei una nuova classe chiamata `SimpleIT` in quella directory. Per inciso, `IT` sta per **integration test** e Maven esegue automaticamente tutte le classi `*IT`. Di seguito è riportato un esempio di come creare questa classe:

**JUnit 4**

```java
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class SimpleIT extends TestBenchTestCase {

    @Before
    public void setup() throws Exception {
        // Create a new browser instance
        setDriver(new ChromeDriver());
        // Open the application
        getDriver().get("http://localhost:8080/");
    }

    @Test
    public void clickButton() {
        // Find the button (<vaadin-button>) on the page
        ButtonElement button = $(ButtonElement.class).single();

        // Click it
        button.click();

        // Check the the value of the button is "Clicked"
        Assert.assertEquals("Clicked", button.getText());
    }

    @After
    public void tearDown() throws Exception {
        // close the browser instance when all tests are done
        getDriver().quit();
    }

}
```

Il supporto JUnit 5 è stato aggiunto in Vaadin 24.

**JUnit 5**

```java
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;

import com.vaadin.testbench.BrowserTest;
import com.vaadin.testbench.BrowserTestBase;

public class SimpleIT extends BrowserTestBase {

    @BeforeEach
    public void setup() throws Exception {
        // Open the application
        getDriver().get("http://localhost:8080/");
    }

    // Please note that since TestBench 9 test methods
    // must be annotated with helper @BrowserTest annotation.
    @BrowserTest
    public void clickButton() {
        // Find the button (<vaadin-button>) on the page
        ButtonElement button = $(ButtonElement.class).single();

        // Click it
        button.click();

        // Check that text of the button is "Clicked"
        Assertions.assertEquals("Clicked", button.getText());
    }

}
```

Questo è tutto ciò che serve per verificare che il testo del pulsante sia "Clicked" dopo averci fatto clic.

In una classe che estende `BrowserTestBase`, chiami `assertEquals()` tramite la classe `Assertions` anziché tramite un import statico, come nell’esempio JUnit 5. `BrowserTestBase` ha un metodo `assertEquals()` deprecato che confronta due elementi. Esso nasconde un `assertEquals()` importato staticamente. Una chiamata `assertEquals()` non qualificata quindi compila solo quando entrambi gli argomenti sono elementi.

> **Note:** WebComponents nascondono il loro contenuto nello Shadow DOM. Questo è il motivo per cui gli elementi all’interno di un WebComponent non possono essere trovati senza specificare un contesto di ricerca. Ad esempio, `$(TestBenchElement.class).id("content").$(SpanElement.class).single()`, che significa che un span dovrebbe essere trovato all’interno dell’elemento con `id="content"`, che dovrebbe essere trovato nella pagina o nel contesto corrente. Per scrivere test reali, usi i [Page or View Objects](https://vaadin.com/docs/latest/it/flow/testing/end-to-end/page-objects.md), che migliorano la leggibilità del codice.

> **Tip:** Non inserisca i suoi test nel package root, come in questo esempio. Li strutturi logicamente in base alla struttura della sua applicazione.

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

Il server che ospita la sua applicazione deve essere in esecuzione all’URL indicato prima di avviare il test. Se il server è già in esecuzione e l’applicazione è deployata, deve solo assicurarsi che l’URL nel test sia corretto.

Se sta usando lo starter Spring Boot su <https://start.vaadin.com>, può avviare l’applicazione usando quanto segue:

```
mvn spring-boot:run
```

Se sta usando uno starter Java Servlet semplice, può avviare l’applicazione usando questo:

```
mvn jetty:run
```

Ora può avviare il test nel suo IDE (esegui come test JUnit) oppure in un altro terminale in questo modo:

```
mvn verify
```

Dovrebbe vedere una finestra del browser che si apre, fa qualcosa, e poi si chiude. Se il test fallisce, inserisca un breakpoint nel metodo `clickButton()` così può vedere cosa succede nel browser prima che si chiuda.

> **Tip:** Poiché il nome del test termina con `IT`, il plugin Maven failsafe riconosce il test come integration test ed è in grado di avviarsi automaticamente e deployare la sua applicazione prima del test e arrestare il server dopo che tutti i test sono stati eseguiti (collegare il server alle fasi `pre-integration-test` e `post-integration-test`). Veda <https://github.com/vaadin/testbench-demo> per un esempio.

\+ L’esecuzione di `mvn test` esegue solo unit tests (`*Test`) per impostazione predefinita, mentre `mvn verify` esegue anche integration tests (`*IT`).

`547F7BA4-9832-4DCB-8900-6E29260D9800`
