How To Automate Login Page Using Selenium WebDriver?

How To Automate Login Page Using Selenium WebDriver?

Selenium has always been the most preferred test automation framework for testing web applications. This open-source framework supports popular programming languages (e.g. Java, JavaScript, Python, C#, etc.), browsers, and operating systems. It can also be integrated with other test automation frameworks like JUnit, TestNG, PyTest, PyUnit, amongst others. As per the State of open source testing survey, Selenium is still the king for web automation testing, with 81% of organizations preferring it over other frameworks.

unnamed-61.png

When it comes to designing a responsive website, the most important feature is the login page. Login functionality plays a critical role from the security perspective of a user or customer. If the login feature acts up, the other website functionalities might not hold good.

In this blog on how to automate login page using Selenium WebDriver, we will take a look at different login mechanisms. Along with it, we will also deep dive into how to automate login page using Selenium WebDriver on a Selenium Grid cloud like LambdaTest for realizing Selenium automation testing.

So, let’s get started!

Wanna take a sneak peek into The Future of testing? Attend the free Testμ 2022 Conf by LambdaTest

Top Authentication Mechanisms

There are different mechanisms used for login purposes. Some of them are mentioned below:

  • Password-based authentication
  • Multi-factor authentication
  • Token-based authentication
  • Certificate-based authentication

Based on its type, the implementation of the Login feature would differ. For example, the user would be asked to authenticate his/her identity in different ways to maintain a high-security level on some websites.

Of all these types, we have the latest authentication type called OAuth2.0 that is designed to allow a web page or application to access resources hosted by another web application on behalf of a user.

There may be multiple scenarios to be handled while testing web applications. However, out of those tests, the most important scenario that should be handled is the login scenario, without which nothing can be tested in the web application. Therefore, the login page has to be tested effectively to test the website (or application) from usability and security perspectives.

To test the login feature of any web application with password authentication, we need to fulfil the below requirements before writing the test case.

  1. Valid URL to test the web application
  2. Valid URL to test the web application

However, we will have different steps for handling different kinds of authentication.

  • For password-based authentication, a combination of username and password has to be passed in the test script
  • For multi-factor authentication, different steps for handling the authentication. Once the user has entered his/her credentials in some web pages, he would be prompted to respond to the push notification sent to the mobile. In such cases, we have to automate the steps for handling the notification.
  • In OAuth authentication, we need to provide various parameters like client ID, secret client ID, etc. Here, tests have to be designed based on the authentication mechanism used in the web application.

Here are a few scenarios that have to be covered as a part of testing login page using Selenium WebDriver:

  1. Testing with different data combinations like upper case, special character, maximum and minimum length and verifying the error message in case of incorrect usage
  2. Masking the password in the password field and verifying the password by clicking the Show Password option
  3. Verifying if the password is stored in an encrypted form
  4. Verifying if the user can copy and paste the password
  5. Verifying two-way authentication (or 2FA) through email and mobile in highly secured websites
  6. Verifying if a logged-in user lands on the login page when the same URL is copied & pasted in a new browser window

We have seen some high-level scenarios to be tested on the login page. In the next section of this article on how to automate login page using Selenium WebDriver, let us see how to implement and test the login functionality.

Login automation using Selenium WebDriver

Consider the below scenario to test the login feature of the LambdaTest web page.

Step 1: Launch the LambdaTest website. (lambdatest.com)

Step 2: Click Login.

Step 3: Enter a valid email and password.

Step 4: Click the Log in button.

Step 5: Verify the title of the page to ensure that the user has successfully logged into the website.

Now let’s see how to write our login test in Selenium WebDriver.

To begin with, we first need to specify the driver’s path and then instantiate the appropriate browser for that driver. Then, depending on our browser choice, we can instantiate the drivers.

Chrome

System.setProperty(“webdriver.chrome.driver”,path_to_browser_driver);
WebDriver driver = new ChromeDriver();

Firefox

System.setProperty(“webdriver.gecko.driver”,path_to_browser_driver);
WebDriver driver = new FirefoxDriver();

Edge

System.setProperty(“webdriver.edge.driver”,path_to_browser_driver);
WebDriver driver =  new EdgeDriver();

Internet Explorer

System.setProperty(“webdriver.ie.driver”,path_to_browser_driver);
WebDriver driver = new InternetExplorerDriver();

To implement our test scenario, we have to identify four web elements:

  • The Login button in the main web page to navigate to the login page
  • Email
  • Password
  • Log in

This is how our web page looks upon launching the site.

unnamed-4.jpg So our first step would be identifying the Login element on the main page. To do that, right-click on the element and click Inspect.

unnamed-62.png Upon clicking Inspect, you could see the attributes displayed for the web element in the Elements tab.

unnamed-63.png

We have eight different locators in Selenium WebDriver that are supported to locate the elements. They are

  • ID
  • Name
  • className
  • tagName
  • linkText
  • partialLinkText
  • CssSelector
  • XPath

We can use any one of the Selenium locators to identify the element in our script.

To identify the login option in the webpage, let us use the LinkText locator in our code and then perform a click action on that element.

WebElement login = driver.findElement(By.LinkText(“Login”);
login.click();

Upon navigating to the login page, the user must enter the valid credentials in the Email and Password textbox.

unnamed-5.jpg

There are also other options to log in to this web page, i.e., by clicking the Log in with Google and Log in with GitHub. Here, we will consider Log in via Google.

Upon clicking this you will be asked to log in through your Gmail account that is used in the device.

unnamed-64 (1).png

If you don’t have any accounts, you will have to provide your email and password, and then the notification will be sent to your mobile as it is the first time you have signed in through this device.

Now let’s proceed with the usual login with email and password.

To identify the Email and Password web elements, right-click and inspect them.

unnamed-65.png

We can use id, name, className, or even XPath to identify this web element.

ID:

driver.findElement(By.id(“email”));

Name:

driver.findElement(By.name(“email”));

className:

driver.findElement(By.className(“(//input[@class=’form-control’])[1])”);

XPath:

driver.findElement(By.xpath(@id=”email”));

Once the web elements are identified, we can use the Selenium sendKeys() method to enter the values. But before entering the values, it is always recommended to clear the text fields, which is considered one of the best practices for Selenium test automation. To do that, we can use the clear() method.

WebElement email = driver.findElement(By.name(“email”));
email.clear();
email.sendKeys(“your_email”);

Next, let us inspect the Password text box.

unnamed-66.png

WebElement password = driver.findElement(By.id(“password”));
password.clear();
password.sendKeys(“your_password”));

After entering the credentials, we have to click the Login button.

To do that, we have to click the Log in button and Inspect it to identify the Log in web element.

unnamed-67.png

WebElement loginButton = driver.findElement(By.id(“login-button”));
loginButton.click();

Now we have identified all the web elements and methods required to automate login page using Selenium WebDriver in the web application.

The final step is to get the web page’s title to ensure that the login has been successful and the user has been logged into the web page to perform further actions.

To get the title of the current web page, we can use the getTitle() method.

String actualTitle = driver.getTitle();
System.out.println(“The title of the web page is+actualTitle);

String expectedTitle = “Welcome – LambdaTest”;

We can use the assertions class to compare the results.

Assert.assertEquals(actualTitle, expectedTitle,"The actual and expected title don’t match");

So whenever the titles don’t match, we can handle them by throwing an error message, “The actual and expected title don’t match”.

And at last, when the test execution is completed, we have to close the browsers used for executing the tests.

You can close the browser by using two different Selenium WebDriver commands, these are:

  • close(): Closes the current browser window.
  • quit(): Quit all the instantiated browser instances.
driver.close();  //it closes the single browser window accessed by the WebDriver instance
driver.quit();    //it closes all the open browser windows instances

Did you know? SHA512 Hash calculator helps you determine the integrity of your data and challenge hash authentication.

Code Snippet to automate login page using 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.Assert;

import java.util.concurrent.TimeUnit;

public class LoginTest {
    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver",path_of_browser_driver);
        WebDriver driver = new ChromeDriver();

        String url = "https://www.lambdatest.com/";

        driver.get(url);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);


        WebElement login = driver.findElement(By.linkText("Login"));
        System.out.println("Clicking on the login element in the main page");
        login.click();

        driver.manage().timeouts().pageLoadTimeout(10,TimeUnit.SECONDS);

        WebElement email = driver.findElement(By.id("email"));
        WebElement password = driver.findElement(By.id("password"));
        WebElement loginButton = driver.findElement(By.id("login-button"));

        email.clear();
        System.out.println("Entering the email");
        email.sendKeys("your_email");

        password.clear();
        System.out.println("entering the password");
        password.sendKeys("your_password");

        System.out.println("Clicking login button");
        loginButton.click();

        String title = "Welcome - LambdaTest";

        String actualTitle = driver.getTitle();

        System.out.println("Verifying the page title has started");
        Assert.assertEquals(actualTitle,title,"Page title doesnt match");

        System.out.println("The page title has been successfully verified");

        System.out.println("User logged in successfully");

        driver.quit();
    }
}

To run the tests locally, right-click your class and click Run.

unnamed-68.png

unnamed-69.png

This certification is for anyone who wants to stay ahead among professionals who are growing their career in test automation using Selenium.

Here’s a short glimpse of the Selenium 101 certification from LambdaTest:

You can follow the LambdaTest YouTube Channel and stay updated with the latest tutorials around Selenium testing, cypress testing , CI/CD, and more.

How to automate login page using Selenium Grid cloud?

With a cloud-based Selenium Grid like LambdaTest, you can now run your Selenium automated test cases on a scalable Selenium infrastructure running real browsers and operating systems. Selenium testing tools like LambdaTest allows you to perform cross browser testing on more than 3000+ online browsers and OS combinations. You can also test on Cypress e2e testing for end to end testing.

To run our tests on Selenium Server, we must first ensure that the prerequisites are met.

The basic setup for running our tests are mentioned below.

Step 1. Create a LambdaTest account

To begin with, you need to create a LambdaTest Account. Upon successful account creation, you can sign in to your account and navigate to the LambdaTest Dashboard. Next, go to the LambdaTest Profile section under the Settings.

unnamed-70.png Here you can find your username and access token, which can be used in your tests to run them in the LambdaTest grid.

unnamed-71.png

These credentials can be defined in your tests.

public String username = "YOUR_USERNAME";
public String accesskey = "YOUR_ACCESSKEY";
public static RemoteWebDriver driver = null;
public String gridURL = "@hub.lambdatest.com/wd/hub";

Step 2. Setting up Desired Capabilities

To run our tests in different browsers and operating systems, we must define the Desired Capabilities

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", browserName);
capabilities.setCapability("version", browser_version);
capabilities.setCapability("platform", platform_name);
capabilities.setCapability("build", buildName);
capabilities.setCapability("name", testName);

In our tests, I have mentioned the desired capabilities for running our tests in a chrome browser with version 93 in Windows 10 operating system.

capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("version", "93.0");
capabilities.setCapability("platform", "win10");

Similarly, you can also define the desired capabilities for other browsers and operating systems. If you are not sure of writing your own desired capabilities, still LambdaTest extends its hand to assist you with it!

You can generate the desired capabilities of different browser and OS combinations using the LambdaTest Desired Capabilities Generator.

unnamed-72.png

Are you looking to Shuffle letters online? This tool generates completely random words from a given input by shuffling their letters. Try shuffling now!

Code Snippet to automate login page using Selenium Grid cloud

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class LoginTest {
    public String username = "YOUR_USERNAME";
    public String accesskey = "YOUR_ACCESSKEY";
    public static RemoteWebDriver driver = null;
    public String gridURL = "@hub.lambdatest.com/wd/hub";

@BeforeClass
public void setUp() throws Exception {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("browserName", "chrome");
        capabilities.setCapability("version", "93.0");
        capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one
        capabilities.setCapability("build", "LoginTest");
        capabilities.setCapability("name", "LoginTestInChrome");
        try {
        driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
        } catch (MalformedURLException e) {
        System.out.println("Invalid grid URL");
        } catch (Exception e) {
        System.out.println(e.getMessage());
        }
        }

@Test()
public void test_1() {

        String url = "https://www.lambdatest.com/";

        driver.get(url);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);


        WebElement login = driver.findElement(By.linkText("Login"));
        System.out.println("Clicking on the login element in the main page");
        login.click();

        driver.manage().timeouts().pageLoadTimeout(10,TimeUnit.SECONDS);

        WebElement email = driver.findElement(By.id("email"));
        WebElement password = driver.findElement(By.id("password"));
        WebElement loginButton = driver.findElement(By.id("login-button"));

        email.clear();
        System.out.println("Entering the email");
        email.sendKeys("your_email");

        password.clear();
        System.out.println("entering the password");
        password.sendKeys("your_password");

        System.out.println("Clicking login button");
        loginButton.click();

        String title = "Welcome - LambdaTest";

        String actualTitle = driver.getTitle();

        System.out.println("Verifying the page title has started");
        Assert.assertEquals(actualTitle,title,"Page title doesnt match");

        System.out.println("The page title has been successfully verified");

        System.out.println("User logged in successfully");      
    }

    @AfterClass
    public void closeBrowser() {
        driver.close();

    }
}

TestNG.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite  name="LoginSuite">

    <test name="LoginTest" >
        <classes>
            <class name="com.MyTests.LoginTest">
            </class>
        </classes>
    </test>
</suite>

In the LambdaTest dashboard, you can see the test which has run.

unnamed-73.png

On further navigating inside, you can see the browser and operating system details on which the test had been run, and also, a video recording of the test execution has been attached for debugging purposes.

unnamed-74.png

LambdaTest supports more than 3000+ browsers and OS combinations that give the ability to perform Selenium automation testing in parallel on any of these combinations. The combinations can be defined in Desired Capabilities, and the rest all remain the same.

The Login feature has to be the same across the browsers and operating systems. Running our tests across different platforms will ensure that the functionality is the same across the platforms. The functionality and the user should have the same experience of using the feature on different platforms.

unnamed-76.png

You can find the list of operating systems and list of browsers for running your tests in the grid. In addition to that, we can also run our tests in parallel on different platforms, which will be very effective in reducing Selenium test execution time.

Let us try running the login tests in two different browsers – Chrome and Firefox.

Code Snippet to automate login page using Selenium WebDriver in parallel

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class LoginTest {
    public String username = "YOUR_USERNAME";
    public String accesskey = "YOUR_ACCESSKEY";
    public static RemoteWebDriver driver = null;
    public String gridURL = "@hub.lambdatest.com/wd/hub";

@BeforeClass
@Parameters("browser")
public void setUp(String browser) throws Exception {

        DesiredCapabilities capabilities = new DesiredCapabilities();

        if (browser.equalsIgnoreCase("Chrome")) {
                capabilities.setCapability("browserName", "chrome");
                capabilities.setCapability("version", "93.0");
                capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one
                capabilities.setCapability("build", "LoginTest");
                capabilities.setCapability("name", "LoginTestInChrome");
        }
        else if (browser.equalsIgnoreCase("Firefox")) {
                capabilities.setCapability("browserName", "Firefox");  //To specify the browser
                capabilities.setCapability("version", "76.0");    //To specify the browser version
                capabilities.setCapability("platform", "win10");      // To specify the OS
                capabilities.setCapability("build", "LoginTest");  //To identify the test
                capabilities.setCapability("name", "LoginTestInFirefox");
        }
        try {
                driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
        } catch (MalformedURLException e) {
                System.out.println("Invalid grid URL");
                } catch (Exception e) {
                        System.out.println(e.getMessage());
                }

}

@Test()
public void test_1() {

        String url = "https://www.lambdatest.com/";

        driver.get(url);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);


        WebElement login = driver.findElement(By.linkText("Login"));
        System.out.println("Clicking on the login element in the main page");
        login.click();

        driver.manage().timeouts().pageLoadTimeout(10,TimeUnit.SECONDS);

        WebElement email = driver.findElement(By.id("email"));
        WebElement password = driver.findElement(By.id("password"));
        WebElement loginButton = driver.findElement(By.id("login-button"));

        email.clear();
        System.out.println("Entering the email");
        email.sendKeys("your_email”);

        password.clear();
        System.out.println("entering the password");
        password.sendKeys("your_password");

        System.out.println("Clicking login button");
        loginButton.click();

        String title = "Welcome - LambdaTest";

        String actualTitle = driver.getTitle();

        System.out.println("Verifying the page title has started");
        Assert.assertEquals(actualTitle,title,"Page title doesnt match");

        System.out.println("The page title has been successfully verified");

        System.out.println("User logged in successfully");


    }

    @AfterClass
    public void closeBrowser() {
        driver.close();

    }
}

TestNG.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" parallel="tests">
    <test name="ChromeBrowserTest">
        <parameter name="browser" value="Chrome"/>
        <classes>
            <class name="com.infa.dqcloud.testcases.profiling.LoginTest">
            </class>
        </classes>
    </test>
    <test name="FirefoxBrowserTest">
        <parameter name="browser" value="Firefox"/>
        <classes>
           <class name="com.infa.dqcloud.testcases.profiling.LoginTest">
            </class>
        </classes>
    </test>

</suite>

In the TestNG.xml file, we defined the browser name to execute our tests in different browsers.

Execution

In the output console, you can see that the tests are executed in two different browsers.

unnamed-77.png

In the LambdaTest dashboard, we can see the tests and the browser configuration in which they ran.

unnamed-78.png

LambdaTest also enables the users with the freedom to get a clear view of their application’s performance and quality. You can now track the health of your automated test cases by going to LambdaTest Analytics under the Automation tab. This page allows you to see which tests have failed and lets you download a report for your records.

unnamed-4.gif

Finally..!

The login feature has always been considered the most important feature of any web application. Handling this feature is simple and pretty straightforward. While testing the login functionality, negative case testing contributes equally to the positive case scenario. In this article on how to automate login page using Selenium WebDriver, we have taken the LambaTest web page to test the Login functionality, and we have seen the way to automate the login functionality using Selenium WebDriver. We have also used cloud testing solutions to run the login test in different browsers to check the cross browser compatibility.

I hope this article on performing login automation using Selenium is really helpful in implementing a login automation scenario using the Selenium WebDriver. Feel free to provide your feedback in the comment section. Try your hands on this and keep exploring. Happy testing…!