Test Login functionality using Selenium with Java

Profile picture for user ksharma

In previous lectures, we have discussed how to launch different browsers. Now, we are good to start with our first script. We will be logging in to automation practice website using our script.

public class AppTest 
{
    WebDriver driver;
	
    @BeforeClass
    public void befClass()
    {
        System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir") + "//drivers//chromedriver");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.get("http://www.automationpractice.com");
    }
	
    @Test
    public void LoginTest()
    {
        WebElement signInLnk = driver.findElement(By.linkText("Sign in"));
        signInLnk.click();
		
        WebElement emailID = driver.findElement(By.id("email"));
        emailID.sendKeys("buzzprograms@gmail.com");

        WebElement passWord = driver.findElement(By.name("passwd"));
        passWord.sendKeys("demo!@#123");
        
        WebElement submitButton = driver.findElement(By.cssSelector("button#SubmitLogin"));
        submitButton.click();		
    }
}

In BeforeClass, we have added steps to launch browser. There are 2 additional steps, one is to maximize the browser and another is implicit wait. Implicit wait we will discuss later in more detail, for now just add it in same way to avoid NoSuchElementException.

In our Test, we have found 4 elements using 4 different locators techniques linkText, ID, name and css selector.

  • WebElement: Represents an HTML element. Generally, all interesting operations to do with interacting with a page will be performed through this interface.
  • findElement(): Find the first WebElement using the given method. This method is affected by the 'implicit wait' times in force at the time of execution. 
  • click(): Click the element. 
  • sendKeys(): Use this method to simulate typing into an element, which may set its value.