How To Test a Login Process With Selenium and Java
Test one of the most essential parts of any website's interface with the most popular open-source automated testing application available.
Join the DZone community and get the full member experience.
Join For FreeAutomation testing at first may sound like a nightmare especially when you have been manual testing business for so long. Looking at the pace with which the need for automation testing is moving, it has become imperative for website testers to deep dive into automation and start learning. To become a pro takes time; it requires knowledge and a deep understanding of numerous automation tools and frameworks. As a beginner in automation testing, you may be looking forward to putting your hands on an open-source testing framework. In this Selenium Java tutorial, I will demonstrate a Selenium login example with Java to help you automate the login process.
Automating a login process using Selenium with Java or any other programming language is the very first step towards becoming a successful automation tester. Without further ado, let’s get started.
Some Prerequisites For Selenium Java Tutorial
Before we begin with our Selenium Java tutorial for the login process, we need to be aware of the prerequisites. To begin with, all applications regardless of the domain they may target usually have a login functionality flow associated with them. Be it e-commerce, banking, medical, or education, all request users to login to the application for further usage. As the name suggests, this tutorial offers a basic level of understanding to help beginners getting started with automation testing using Selenium and Java. We will be looking into a Selenium login example with Java (one of the most versatile languages used for multiple techniques and field). In order to kick-start this, you need to have a basic understanding of Java. First, make sure you have all the prerequisites to start writing your first login script using Java and Selenium. You need to have the following:
- Download and Install JDK (Java Development Kit) from here.
- Install Eclipse from the official website.
- Download the Selenium Java Client version from here.
- Driver executable: Depending upon the browser you wish to execute your script in, you can choose to download its Selenium executable from here. As you go down the page, various browsers like Chrome, Mozilla, Opera, and Edge drivers will be available for download to help you perform automated cross-browser testing using Selenium.
That is all. Open Eclipse and create your project. Add your Selenium jar in your Java build path and you are good to go.
Basic Steps For A Selenium Test Case
Before we perform automation testing for login validation using Selenium and Java, there are some basic steps that need to be followed for whichever test case you intend to write. If you follow them, you will never have incomplete test cases in your automation suite:
- Create a Selenium WebDriver instance.
- Configure your browser if required (for example, maximize browser, disable browser notifications, etc.).
- Navigate to the required URL (webpage).
- Locate the HTML element.
- Perform the action on the located HTML element.
- Verify and validate the action (concluded step).
- Take screenshots and generate the report using a framework for the test cases.
If you are planning to devise an automation testing strategy for your organization but are confused about where to start from, follow my blog to start automation testing from scratch.
Let’s Automate Selenium Login With Java
The script I will be mentioning in the article below will be referencing these steps. We will not be considering step seven, as that would require a dedicated article and I plan to do so in my upcoming blogs, so stay tuned! Now, let us look into those steps in detail to help us perform automation testing using Selenium for login with Java:
1. Create A Selenium WebDriver Instance
Webdriver driver=new ChromeDriver();
In order to launch the website in the desired browser, you need to set the system properties to the path of the driver for the required browser. In this Selenium Java tutorial, we will use Chromedriver for demonstrating Selenium login example with Java. The syntax for the same will be:System.setProperty(“webdriver.chrome.driver”, “File path for the Exe”);
2. Configure Your Browser If Required
Based on the needs, we can configure the browser. For example, in this Selenium Java tutorial regarding Selenium login with Java, a browser, by default, will be in minimized mode. However, we can set up the browser in the maximize mode. Below is the syntax.driver.manage().window().maximize();
Other things that you can do for configuring your browser is set up different options like disabling info bars, browser notifications, and adding extensions. You can also use the capabilities class to run your script on various browsers, thereby helping in cross-browser testing.
3. Navigate To The Required URL
Open the browser with the desired URL. All you have to do is write the below syntax and you have your URL open in the desired instantiated browser.driver.get(“https://www.linkedin.com/login”);
4. Locate The HTML Element
This is the heart of writing a Selenium script. For this to function, you need to have a clear understanding of the different locators used to find the HTML element. You can refer my below articles that talks about the different locators available in Selenium and how to locate the element with different examples:
- ID locator in Selenium WebDriver
- Name Locator in Selenium WebDriver
- TagName Locator in Selenium WebDriver
- CSS Selector in Selenium WebDriver
- XPath in Selenium WebDriver
For example, let's try to locate the email and password field of the login form of LinkedIn
Below is the DOM structure for the email input box:
You can locate it via ID locator in Selenium WebDriver as below:driver.findElement(By.id(“username”));
Since this returns a web element, you can store it in web element variable as below:WebElement username=driver.findElement(By.id(“username”));
The same can be achieved for password and login button field which is
Format:
driver.findElement(By.id(“password”)); WebElement password=driver.findElement(By.id(“password”)); driver.findElement(By.xpath(“//button[text()=’Sign in’]”)); WebElement login= driver.findElement(By.xpath(“//button[text()=’Sign in’]”));
5. Perform Action On The Located HTML Element
Once located, you need to perform the desired action which in our case is sending text to email and password field and clicking on the login button. To execute this action in Selenium login example with Java, we make use of methods sendKeys
and click
provided by Selenium as below:
Format:
username.sendKeys(“xyz@gmail.com”); password.sendKeys(“exampleAboutSelenium123”); login.click();
You just finished writing the most important parts of the script. Now, in this Selenium Java tutorial, you only need to ensure these actions have successfully logged in the user, which comes to our final step of script creation for using Selenium to login with Java.
6. Verify & Validate The Action
In order to validate the results, all you need to do is use an assertion. Assertions are vital for comparing the expected results and the actual results. Almost similar to your test cases, wherein each test case has an actual and expected behavior to it. If it matches, the test case pass, if not, then the test case fails. Assertions do exactly the same. Assertion class are provided by both JUnit and TestNG framework, and you can opt to choose either. The below syntax will help to assert (validate) the outcome from actions by performing Selenium login with Java.
Assert.assertEquals(String actual, String expected);
So, in this case, we will save our actual URL post login into a string value which is:String actualUrl=” https://www.linkedin.com/feed/”;
And expected URL can be found from the below method:
String expectedUrl= driver.getCurrentUrl();
So your final assertion would become as:
Assert.assertEquals(actualUrl, expectedUrl);
Note: In order to use assertion, you need to use the annotations of TestNG or JUnit "@Test" for assertions to function. In case, right now you don’t want to get into the hassle of going into the framework keywords, you can simply match the string using an "if" statement and print the results in console accordingly, something like below:
Format:
if(actualUrl.equalsIgnoreCase(expectedUrl)) { System.out.println(“Test passed”) } else { System.out.println(“Test failed”) }
You have executed automation testing using Selenium login example with Java.
Below is the collective code of all the statements explained above using assertions.
import java.util.concurrent.TimeUnit;
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 LoginUsingSelenium {
@Test public void login() { // TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "path of driver");
WebDriver driver=new ChromeDriver(); driver.manage().window().maximize();
driver.get("https://www.linkedin.com/login");
WebElement username=driver.findElement(By.id("username"));
WebElement password=driver.findElement(By.id("password"));
WebElement login=driver.findElement(By.xpath("//button[text()='Sign in']"));
username.sendKeys("example@gmail.com"); password.sendKeys("password");
login.click(); String actualUrl="https://www.linkedin.com/feed/";
String expectedUrl= driver.getCurrentUrl();
Assert.assertEquals(expectedUrl,actualUrl); } }
Console Output:
Below is the collective code of all the statements explained above using the if statement:
import java.util.concurrent.TimeUnit;
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;
public class LoginUsingSelenium {
public static void main(String[] args) { // TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", " path of driver ");
WebDriver driver=new ChromeDriver(); driver.manage().window().maximize();
driver.get("https://www.linkedin.com/login");
WebElement username=driver.findElement(By.id("username"));
WebElement password=driver.findElement(By.id("password"));
WebElement login=driver.findElement(By.xpath("//button[text()='Sign in']"));
username.sendKeys("example@gmail.com"); password.sendKeys("password");
login.click(); String actualUrl="https://www.linkedin.com/feed/";
String expectedUrl= driver.getCurrentUrl(); if(actualUrl.equalsIgnoreCase(expectedUrl)) {
System.out.println("Test passed"); } else { System.out.println("Test failed"); } } }
Console Output:
Moving Selenium Tests On Cloud
Selenium empowers automation testers to fast track their efforts and test cycles. However, with the benefits of Selenium WebDriver, there comes some cons, too. The most prominent ones include the sequential execution of tests which can take a while for larger automated test suites. Keeping that in mind, the Selenium Grid was introduced to help people run Selenium tests in parallel. However, there is a downside to that as well and that is test coverage and CPU consumption. You can only perform browser compatibility testing on browsers that are installed on your local machine. Installing numerous browsers isn’t a feasible consideration.
How Was That?
Kudos! You have successfully executed automation testing for login process using Selenium & Java. How did you find this Selenium Java tutorial for login process? Let me know your thoughts in the comment section below. I look forward to your replies. Happy testing!
Published at DZone with permission of Sadhvi Singh. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments