x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Selenium Junit test example

    Selenium is an open source tool used to test web applications. Selenium uses WebDriver which makes call to the browsers like Chrome, Firefox, Microsoft Edge. In this example we will show how to run a Selenium test using JUnit framework. We will run two tests, one will launch google home page, second test will enter keywords in google text box.

    You can download web drivers from this link Selenium download. Latest chrome driver can be downloaded from this link ChromeDriver

    Configuring and running Selenium tests using Junit

    Step 1) Add maven dependencies

    Maven dependencies


    Gradle dependencies

    dependencies {
        implementation group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.141.59'

    Step 2) Write test class to run Selenium tests

    In ChromeSeleniumTest, first test will launch google home page and validate page title. Second test will enter keywords in google text box and provide search results.

    package selenium;
    import static org.junit.jupiter.api.Assertions.assertEquals;
    import org.junit.jupiter.api.AfterEach;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    public class ChromeSeleniumTest {
        private WebDriver driver;
        void setUp() {
            driver = new ChromeDriver();
        void testGoogle() {
            assertEquals(driver.getTitle(), "Google");
        void testGoogleSearch() {
            WebElement r = driver.findElement(By.name("q"));
            r.sendKeys("junit selenium");
            r = driver.findElement(By.xpath("//*[@id=\"Odp5De\"]/div/div[1]/div[1]/span/div/div/div/div"));
            assertEquals("JUnit Selenium", r.getText());
        void tearDown() {

    Finding an element in browser

    When you write a Selenium test you may want to validation particular field in the browser. To identify it, you can use XPath. In the browser right click on 'Google Search' button and select 'Inspect'. Then go the the highlighted element under 'Elements' tab and right click, select copy, select 'copy XPath'. Now this XPath can be used in the code to find the element. driver.findElement(By.xpath("/html/body/div[1]/div[3]/form/div[1]/div[1]/div[4]/center/input[1]"));

    Selenium XPath

    Selenium XPath

    Selenium XPath

    Selenium XPath

    References :



    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Share This