In the below mentioned script the following user actions are performed:-
- User opens the browser.
- User enter the URL of google home page and lands on the Google home Page.
- User clicks on the search box and provided input text “Selenium Test”.
- User waits for 4000 mill seconds.
- User clicks on the Search button.
- Now one assertion written to validate the Title of the newly opened page.
Under AfterMethod annotation quit browser method is written to close and quit from the session.
And at the starting point, System property set and the path of the Chromedriver.exe is provided manually so that the chrome driver can be launched by the Selenium WebDriver.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; public class LocateElements { /** * Global variable */ WebDriver driver; /** * Before Running any test, set up the chrome driver */ @BeforeMethod public void setUpChromeDriver() { System.setProperty("webdriver.chrome.driver" , "src/lib/chromedriver.exe"); //new Chrome driver instance of WebDriver class driver = new ChromeDriver(); //get method of webDriver class driver.get("https://www.google.com"); } @Test public void searchGoogleMainPage() throws InterruptedException { //WebelEment is the interface WebElement searchBox = driver.findElement(By.name("q")); //click method of webElement interface searchBox.click(); //sendKeys method of WebElement interface searchBox.sendKeys("Selenium Test"); Thread.sleep(4000); WebElement searchButton = driver.findElement(By.className("gNO89b")); searchButton.click(); //assertion to verify the title of newly opened google page assertThat(driver.getTitle()).isEqualTo("Selenium Test - Google Search"); } @AfterMethod public void closeBrowser() { //It will quit the driver driver.quit(); } }
For other sample code, please visit the site. And for Selenium related interview questions please visit here.
The Script can be executed using TestNg as shown in the below videos link.