When it comes to automating web application testing, Selenium is the first tool that comes to mind. Selenium is a cross-platform software testing framework for web applications that supports multiple languages such as Java, C#, Ruby, Python, and others. The application under test, the supporting community, available test automation frameworks, usability, elegance, and seamless build integration all play a role in selecting the correct language. In this article, you will learn how to create a basic test case in Selenium IDE. So let us dive in!
Prerequisites
Before configuring Selenium, it's necessary to set up several other dependencies. To get started with Selenium automation, you'll need the following items:
Java (JDK).
Eclipse.
Selenium Client and WebDriver Language bindings.
Configuring Selenium Webdriver with Eclipse.
Creating and Running the first test.
After completing the preceding steps, you're ready to write your first Selenium test case. Let's use Selenium WebDriver to automate the following user journey:
Enter your credentials to access the website. Our test script will use the login username - 'testuser' and password- 'Password@123'.
Check to see if the LogOut button is active.
Finally, we log off of the website.
Let's start writing our first Selenium test case, one step at a time.
Opening Browser
"Open a Browser" is the first step in automating any test case with Selenium WebDriver. Selenium WebDriver has multiple drivers for different browsers, such as ChromeDriver for Chrome, InternetExplorerDriver for Internet Explorer, and GeckoDriver for Firefox. As a result, you can select the desired driver and launch the WebDriver for the specified browser, depending on your needs.
As we all know, WebDriver is an interface that can be instantiated using any browser's driver class. The following are some examples of how to use the WebDriver with the Firefox and Chrome drivers:
Instantiate WebDriver using Firefox Driver:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
System.setProperty("webdriver.gecko.driver", "<Gecko Driver executable location on your system>");
WebDriver driver = new FirefoxDriver();
Instantiate WebDriver using Chrome Driver:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
System.setProperty("webdriver.chrome.driver", "Chrome Driver executable location on your system");
WebDriver driver = new ChromeDriver();
Import WebDriver packages
As we can see, both the above code snippets start with two import statements.
import org.openqa.selenium.WebDriver; – This import statement references the WebDriver interface that instantiates the browser.
import org.openqa.selenium.firefox.FirefoxDriver; , import org.openqa.selenium.chrome.ChromeDriver; – References the Driver class, which instantiates browser drivers using the WebDriver interface.
Set path of browser driver
Selenium WebDriver expects an external executable from Selenium 3 onwards to act as a communication medium between the Selenium test and the corresponding browser. Furthermore, the executable's path must be specified explicitly. The "System.setProperty" method can be used to set up various driver specific properties, such as "webdriver.chrome.driver" for chrome and "webdriver.gecko.driver" for firefox, among other things.
Object Instantiation of WebDriver
The fourth and most important statement is to reference the WebDriver interface to create an Object of driver class. This object/instance will, as previously stated, call various WebDriver methods in our test script. Let's take the case of chrome as an example.
WebDriver driver = new ChromeDriver();
The code above will start a Chrome browser in safe mode without plugins or extensions.
Navigating to a Web Page
We'll navigate to the desired web page once the WebDriver has been instantiated. You can navigate to a specific web page in Selenium WebDriver using one of two methods.
driver.get("URL"): Navigates to the URL specified in the argument and waits for it to load.
driver.navigate().to("URL"): The URL passed as an argument is navigated to without waiting for the page to load. It also keeps track of your browser history so you can go back and forth.
You can use either of these two methods, but the get() method is generally preferred because it will prevent any further action until the page has fully loaded. In our examples, we'll use the get() method. Furthermore, the code for it would be as follows:
driver.get("https://demoqa.com/login");
The driver variable would use the get() method to navigate to the website URL, which is passed as a String argument.
In most cases, Selenium WebDriver does not open the browser in a full window, as this is how users use any browser. As a result, even when automating tests, we should open the browser in full-screen mode.
Maximize browser window
It is possible that Selenium WebDriver won't launch the browser in full size. A simple line of code can be used to maximize the browser window at any time.
driver.manage().window().maximize();
Whereas the manage() method previously returned an instance of the Options interface, the Options interface now has a window method that returns a Window type. The browser window is then maximized using the Window interface's maximize method.
Retrieve the title of the page
The getTitle() method, like the get() method, is an intriguing WebDriver feature. The title of the currently open web page is retrieved and returned as a String. The driver variable in the code below calls the getTitle() method and saves the results in the 'title' string variable. We then use the Java print statement to print this string variable on the console window:
String title = driver.getTitle();
System.out.println("The page title is : " +title);
So, now that we've learned about Selenium WebDriver, different browser-specific methods, and how to navigate to a specific page, maximize the browser and get the title of the currently open webpage in the browser, let's move on to the next step.
Locating a web element on a web page
Locating the web elements we want to interact with is the next step in writing the automation scripts. Selenium WebDriver has several locator strategies for locating various web elements on a page. All of these locators are provided by the "By." Selenium WebDriver is a type of Selenium WebDriver. We used the XPath locator strategy to locate the userName, password, and login button elements in our example scenario, as shown below:
As you can see, the various Web Elements store variables that are used to perform actions on them. Two more import statements will be added to your code as a result of this:
import org.openqa.selenium.By; – It refers to the By class, which is used to call the locator type.
import org.openqa.selenium.WebElement; – It makes use of the WebElement class, which aids in the creation of a new web element.
Performing Actions on Web Elements
We'll perform actions on the web elements after locating them and saving them as WebElement instances, such as entering text for the user name and password and clicking the login button. Selenium WebDriver has several methods for performing actions on different web elements. The WebElement interface exposes the following methods:
sendKeys() is a function used to enter text into a web element.
submit() is a method for submitting a form.
click() is a function used to perform a click on a web element.
clear() is a function that clears the text that has been entered.
For example, we can enter the user name and password using the methods described above, as shown below:
After completing the corresponding actions on the web elements, we should perform validations on selected web elements to ensure that the action we performed successfully resulted in the element's desired state.
For example, in the test user journey, the logout button should be visible once we have successfully logged in to the Demo Site. Let's look at how we can check for the logout button's visibility and then click it if it's there:
After that, we use the "isDisplayed()" method to see if it's visible.
If this is the case, we proceed to click it and print the success message. If this is not the case, the error message is printed. You'll notice that we've enclosed our code in a try-catch block. Our test script would fail because there could be an exception if the login credentials were incorrect. We can handle such situations and gracefully exit execution by using the try-catch block.
Closing the browser
The final step in closing your test script is to close the browser. Selenium WebDriver provides the following methods for closing the browser:
close() – The current browser window is closed.
quit() – It invokes the WebDriver's dispose() method, which closes all of the WebDriver's browser windows and ends the WebDriver session. The quit() method is always recommended because it releases the driver.
The driver uses the code below to call the quit method.
driver.quit();
Now we can combine all of the previous steps to create the complete test script. The following is the consolidated code:
package firstPackage;
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;
public class MyFirstTestClass {
public static void main(String[] args){
//Setting the driver path
System.setProperty("webdriver.chrome.driver", "E:\\Softwares\\chromedriver.exe");
//Creating WebDriver instance
WebDriver driver = new ChromeDriver();
//Navigate to web page
driver.get("https://demoqa.com/login");
//Maximizing window
driver.manage().window().maximize();
//Retrieving web page title
String title = driver.getTitle();
System.out.println("The page title is : " +title);
//Locating web element
WebElement uName = driver.findElement(By.xpath("//*[@id='userName']"));
WebElement pswd = driver.findElement(By.xpath("//*[@id='password']"));
WebElement loginBtn = driver.findElement(By.xpath("//*[@id='login']"));
//Peforming actions on web elements
uName.sendKeys("testuser");
pswd.sendKeys("Password@123");
loginBtn.click();
//Putting implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try {
//Locating web element
WebElement logoutBtn = driver.findElement(By.xpath("//div[@class='text-right col-md-5 col-sm-12']//button[@id='submit']"));
//Validating presence of element
if(logoutBtn.isDisplayed()){
//Performing action on web element
logoutBtn.click();
System.out.println("LogOut Successful!");
}
}
catch (Exception e) {
System.out.println("Incorrect login....");
}
//Closing browser session
driver.quit();
}
}
Run Selenium Test Case
A Selenium test case's execution depends on how it was written and which test executor was used. There are a variety of test executors available, such as Junit and TestNG, but to keep things simple, we've put everything in the "main" method of the Java class so that we can run this test script just like any other Java class. Let's look at how we can accomplish this using the Eclipse IDE:
Assume that the above Selenium test script was saved as "MyFirstTestClass" in the package "firstPackage." The following are the steps we take to run the test script:
Go to Run > Run As > Java Application. Alternatively, right-click the Eclipse code and select Run As > Java Application from the context menu.
Following that, the Chrome browser will open, and the demo website will open as per our script. The title captured by the test script will appear in the Eclipse console window, followed by Login. Upon completion, you will see a successful logout. The console logs should look like this, and you've completed your first Selenium WebDriver test script!
What does “import org.openqa.selenium.WebDriver;” statement do? This import statement references the WebDriver interface that instantiates the browser.
What statements can be used to navigate to a specific web page in Selenium WebDriver? The following statements can be used: –driver.get("URL") – driver.navigate().to("URL")
How to maximize browser window using Selenium WebDriver? The following line of code can be used to maximize the browser window: driver.manage().window().maximize();
What methods can be used to close the browser window using Selenium? The following methods can be used to close the browser window: – close() – quit()
What method can be used to enter text in the web element using Selenium? The sendKeys() method is used to enter text in the web element.
Conclusion
We learned how to write your first Selenium WebDriver test script step by step, covering all necessary actions, find the Web Elements you want to work with, and perform them in this article. We went over the most basic selenium commands, such as wait, and we'll use them in your first script. We now know how to use Java concepts to validate your web pages using Selenium WebDriver. We learned how to run the tests quickly using either the Eclipse IDE or the command line. We hope that this blog has helped you enhance your knowledge regarding first test cases using Selenium and if you would like to learn more, check out our articles on Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!