Test Login Automation in Selenium on Real Devices with BrowserStack

Run Selenium Tests for Login Automation in real user conditions with BrowserStack Automate's real device cloud

Get Started free
Home Guide Login Automation using Selenium Webdriver: Tutorial

Login Automation using Selenium Webdriver: Tutorial

By Neha Vaidya, Community Contributor -

Execution of automation testing requires a comprehensive understanding of numerous automation tools and frameworks. Among these tools, Selenium is the most popular due to its ease of use and relevant features. Selenium is used to automate tests on websites to monitor their performance.

A fundamental feature of many websites is their login function. Automating the testing of this feature is simple enough when using Selenium WebDriver, as this article will demonstrate.

Let’s get started.

Selenium WebDriver allows testers to choose a programming language to create test scripts. It cannot handle window components, but this drawback can be overcome by using tools like Sikuli, Auto IT, etc.

Prerequisites for Login Automation using Selenium Webdriver

  • Download and Install JDK(Java Development Kit)
  • Install Eclipse from the official website
  • Download the Selenium Java Client version
  • Configure the drivers depending on the browser. The example here will be using a chrome driver for Chrome

Steps for Login Automation using Selenium WebDriver

Before performing automation testing for the login functionality, there are a couple of basic steps that need to be followed for the test case to be written:

  1. Create a Selenium WebDriver instance
  2. Configure browser if required
  3. Navigate to the required web page
  4. Locate the relevant web element
  5. Perform action on the web element
  6. Verify and validate the action

Now let’s walk through each of these steps in detail.

1. Create a Selenium WebDriver instance

To launch the website in the desired browser, set the system properties to the path of the driver for the required browser. This example will use ChromeDriver for Login Automation using Selenium Webdriver. The syntax for the same will be:

Webdriver driver = new ChromeDriver();
System.setProperty("webdriver.chrome.driver", "Path of the chrome driver");

2. Configure the Web browser

Usually, the web page will be in a minimized format when the test case is run. Maximize the browser for a clear picture of the test cases executed. Use the command below to do the same:

driver.manage.window.maximize();

3. Navigate to the web URL

Open the browser with the desired URL. Use the command below to open the URL in the desired instantiated browser:

driver.get("https://www.browserstack.com/users/sign_in");

4. Locating the Web Element

Locators are an essential part of every Selenium script as they identify the elements that the test script will interact with to replicate user actions.

For example, let’s try to locate the email and password field of the login form of Browserstack sign in page.

BrowserStack Sign in page

Run Selenium Tests on Real Browsers Free

Inspect the email field to locate the element using the ID locator, as shown in the image below:

Selenium login script

Locate it via the ID locator in Selenium WebDriver:

driver.findElement(By.id("user_email_login"));

Since this returns a webelement, store it in webelement variable with:

WebElement username=driver.findElement(By.id("user_email_login"));

Repeat the same steps for the password field.
Selenium login script example

driver.findElement(By.id("user_password"));
WebElement password=driver.findElement(By.id("user_password"));

Run Selenium Tests for Free

5. Perform Action on the Located Web Element

After locating the element, testers need to perform the desired action. In this case, the action is entering text in the email and password fields and hitting the login button. For this, the script uses sendKeys and click methods, as shown below:

username.sendKeys("abc@gmail.com");
password.sendKeys("your_password");
login.click();

6. Verify & Validate The Action

To validate the results, use assertion. Assertions are important for comparing the expected results to the actual results. If it matches, the test case passes. If not, then the test case fails. The syntax below will help to assert (validate) the outcome from actions by performing login automation:

Assert.assertEquals(String actual, String expected);

Save the actual URL post-login into a string value, which is:

String actualUrl="https://www.browserstack.com/users/sign_in";

The Expected URL can be identified by using the method below:

String expectedUrl= driver.getCurrentUrl();

The final assertion would look like:

Assert.assertEquals(actualUrl, expectedUrl);
If the test case is passed, it will retrieve the same. Else it will return as failed.

Note: Testers need to use JUnit or TestNG to check for the test case status.

Given below is the full selenium code for automating login page in chrome 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 org.testng.annotations.Test;
public class LoginAutomation {
@Test
public void login() {
System.setProperty("webdriver.chrome.driver", "path of driver");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.browserstack.com/users/sign_in");
WebElement username=driver.findElement(By.id("user_email_Login"));
WebElement password=driver.findElement(By.id("user_password"));
WebElement login=driver.findElement(By.name("commit"));
username.sendKeys("abc@gmail.com");
password.sendKeys("your_password");
login.click();
String actualUrl="https://live.browserstack.com/dashboard";
String expectedUrl= driver.getCurrentUrl();
Assert.assertEquals(expectedUrl,actualUrl);
}
}

Talk to an Expert

Run Login Automation using Selenium WebDriver

import java.net.MalformedURLException;

import java.net.URL;

import java.util.HashMap;



import org.openqa.selenium.By;

import org.openqa.selenium.MutableCapabilities;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.testng.Assert;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;



public class LoginAutomation {

    
    public static String username = "<username>";

    public static String accesskey = "<access key>";

    public static final String URL = "https://" + username + ":" + accesskey + "@hub-cloud.browserstack.com/wd/hub";

    WebDriver driver;

    String url = "https://www.browserstack.com/users/sign_in";

    MutableCapabilities capabilities = new MutableCapabilities();

    HashMap<String, Object> bstackOptions = new HashMap<String, Object>();
    

    @BeforeTest

    public void setUp() throws MalformedURLException {

        capabilities.setCapability("browserName", "Chrome");

        bstackOptions.put("os", "Windows");

        bstackOptions.put("osVersion", "11");

        bstackOptions.put("browserVersion", "latest"); 

        bstackOptions.put("consoleLogs", "info"); 

        bstackOptions.put("seleniumVersion", "3.14.0");

        capabilities.setCapability("bstack:options", bstackOptions);

        driver = new RemoteWebDriver(new URL(URL), capabilities);

        driver.get(url);

        driver.manage().window().maximize();

    }   
    

    @Test

    public void login() {       

        //driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));

        WebElement username = driver.findElement(By.cssSelector("input#user_email_login"));

        WebElement password = driver.findElement(By.cssSelector("input#user_password"));

        WebElement login = driver.findElement(By.name("commit"));

        username.sendKeys("youremail@domain.com");

        password.sendKeys("yourpassword");

        login.click();

        String actualUrl = "https://live.browserstack.com/dashboard";

        String expectedUrl = driver.getCurrentUrl();

        Assert.assertEquals(expectedUrl, actualUrl);

    }

}

After running the above programs, you can check the result on the Automate Dashboard page. 

BrowserStack Automate Banner 6

Why Run Selenium Login Tests using Real Device Cloud?

Testing login functionality is crucial as it is the entry point for most of the commercial web applications. Without login one cannot use the application and hence it is obligatory to test the login functionality for any authorization-based web applications.

Also it is pivotal to test login functionality of web applications in latest devices and browsers because all the devices and browsers are not the same. Devices come in different sizes, dimensions, and resolution; similarly browsers also render web pages differently. 

In today’s ever growing mobile market it is not feasible to procure and test on all the latest devices and browsers. To cope with this issue, it is best to invest in any platform which aids in testing the application on a wide range of devices and browsers. 

BrowserStack Automate is one of the cloud-based platforms that provides a comprehensive infrastructure for cross-device and cross-browser testing with zero hassle in setting up the device and environment. 

To ensure a positive user experience, reliability, performance and compatibility of the application across a diverse range of devices, browsers and platforms, testing on real devices is unavoidable.

Conclusion

On executing the code, Selenium will navigate to the Chrome browser and open the BrowserStack login page. Then, it will log in using the relevant credentials. It will also check the test case status using Assert and try to match the URL.

Follow the steps and protocol detailed above to automate the login function of websites with Selenium. Remember to leverage the power of real browsers and devices along with Selenium’s many abilities to create immediately effective test scripts that generate desirable results with minimal time and effort.

It is always recommended to run Selenium Tests on real devices to take real user conditions into account and ensure better accuracy. BrowserStack Real Device Cloud provides access to 3500+ real devices and browsers for a seamless and comprehensive testing experience. You can also run multiple tests on different browser-device combinations with parallel testing using BrowserStack Cloud Selenium Grid.

Try BrowserStack Now

Tags
Automation Testing Selenium Selenium Webdriver

Featured Articles

Exception Handling in Selenium WebDriver

Cross Browser Testing in Selenium : Tutorial

Test Login Automation in Selenium on Real Devices

Use BrowserStack Automate to Run Selenium Login Automation Tests on Real Devices & Browsers