0
0
Selenium Javatesting~5 mins

First Selenium Java test

Choose your learning style9 modes available
Introduction

We write a Selenium Java test to check if a website works as expected automatically. This saves time and avoids mistakes from checking by hand.

You want to check if a website loads correctly.
You want to test if a button on a page works.
You want to make sure a page title is correct.
You want to repeat the same test many times without doing it yourself.
Syntax
Selenium Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class FirstTest {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");
        String title = driver.getTitle();
        if (title.equals("Example Domain")) {
            System.out.println("Test Passed");
        } else {
            System.out.println("Test Failed");
        }
        driver.quit();
    }
}

Use WebDriver to control the browser.

driver.get() opens the website URL.

Examples
This opens Chrome browser and goes to example.com.
Selenium Java
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
This gets the page title and prints it.
Selenium Java
String title = driver.getTitle();
System.out.println(title);
This checks if the title is exactly "Example Domain" and prints the test result.
Selenium Java
if (title.equals("Example Domain")) {
    System.out.println("Test Passed");
} else {
    System.out.println("Test Failed");
}
Sample Program

This test opens Chrome, goes to example.com, checks the page title, prints if the test passed or failed, then closes the browser.

Selenium Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class FirstTest {
    public static void main(String[] args) {
        // Set the path to chromedriver executable if needed
        // System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");

        String title = driver.getTitle();

        if (title.equals("Example Domain")) {
            System.out.println("Test Passed");
        } else {
            System.out.println("Test Failed");
        }

        driver.quit();
    }
}
OutputSuccess
Important Notes

Make sure you have the ChromeDriver installed and its path set correctly.

Close the browser with driver.quit() to free resources.

Use exact text in equals() to avoid false failures.

Summary

Selenium Java tests automate browser actions.

Open a browser, visit a page, check something, then close the browser.

Print results to see if the test passed or failed.