Java - Exemple de Test Selenium

pom.xml Maven

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>fr.ronanlefichant</groupId>
	<artifactId>seleniumtest</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>4.1.2</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

Test JUnit

package fr.ronanlefichant.seleniumtest;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.time.Duration;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

class SeleniumTest {

  @Test
  void should_search() {
    // Les pilotes du navigateur
    System.setProperty("webdriver.gecko.driver", "geckodriver.exe");

    // Le pilote du navigateur (Firefox et Gecko ici)
    WebDriver driver = new FirefoxDriver();

    // Navigue vers la page
    driver.get("https://start.duckduckgo.com/");

    // Cherche l'élément q et écrit "Java Selenium"
    driver.findElement(By.name("q")).sendKeys("Java Selenium");

    // Clique sur le bouton avec ID
    WebElement searchbutton = driver.findElement(By.id("search_button_homepage"));
    searchbutton.click();

    // Attend 10 secondes
    WebDriverWait web = new WebDriverWait(driver, Duration.ofSeconds(10));

    try {
      // Vrai si dans les 10 secondes l'URL est "https://duckduckgo.com/?q=Java+Selenium&ia=web"
      boolean correctURL = web.until(ExpectedConditions.urlToBe("https://duckduckgo.com/?q=Java+Selenium&ia=web"));
      assertTrue(correctURL);
    } finally {
      // Quitte
      driver.quit();
    }

  }

}

Commentaires