A Selenium WebDriver is an open source tool for automating the testing of web applications across many browsers. Selenium supports multiple web browsers such as IE, Firefox, Chrome etc. Selenium Webdriver is used to control the browser.
Here in this article we are creating a script which will perform the following steps.
- Open c-sharpcorner's homepage.
- Verify the title of homepage
- Comparing and print out the result of comparison
- Closing the Browser Session
Steps to perform the above mentioned scenario:
Step 1: Open Eclipse ID and create a new java project and name it 'FirstSeleniumProject'.
Step 2: Right click on the project name and add a new package and name it 'mypackage'.
Step 3: Right click on the project name and add a new class and name it 'myclass'.
Step 4: Now add all selenium library jar files by right click on the project name and select Configure build path from Build Path option.
Step 5: Copy and paste the following code in the myclass class.
- package mypackage;
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.firefox.FirefoxDriver;
- public class myclass
- {
- public static void main(String[] args)
- {
-
- WebDriver driver = new FirefoxDriver();
-
- driver.get("http://www.c-sharpcorner.com");
- String expectedTitle = "C# Corner - Developers and IT Professionals Community";
-
- String actualTitle = driver.getTitle();
-
- if (actualTitle.equals(expectedTitle))
- {
- System.out.println("Test Passed!");
- }
- else
- {
- System.out.println("Test Failed");
- }
-
- driver.close();
- }
- }
Explaining the code
Importing Packages
We need following packages to proceed further:
- org.openqa.selenium.*: This package contains the WebDriver class needed to instantiate a new browser.
- org.openqa.selenium.firefox.FirefoxDriver: This package contains the FirefoxDriver class needed to instantiate a Firefox-specific driver.
Instantiating objects and variables
-
- WebDriver driver = new FirefoxDriver();
With the above statement the default Firefox profile will be launched because no parameter is passed with the FirefoxDriver class. No extensions are loaded in the default Firefox profile which is similar to launch Firefox in safe mode.
Launching a Browser Session
get() method is used to redirect a newly launched browser session to the URL passed as an parameter.=
-
- driver.get("http://www.c-sharpcorner.com");
Compare the Expected and Actual Values
With the help of a basic if-else structure we are comparing the actual title with the excepted title.
-
- if(actualTitle.equals(expectedTitle)){
- System.out.println("Test Passed!");
- }else{
- System.out.println("Test Failed");
- }
Terminating a Browser Session
With the "close()" method we can close the browser session.
Running the Test
We can execute the code in Eclipse IDE. by clicking on Eclipse's menu bar, click Run > Run.
If you did everything correctly, Eclipse will output "Test Passed!"