Scientech Easy How to write First Selenium WebDriver Script | Scientech Easy

Saturday, December 15, 2018

How to write First Selenium WebDriver Script

In this tutorial, we will learn to write first Selenium WebDriver automation script in a very simple way and step by step. Let's start to automate a very simple scenario using Selenium WebDriver and see the explanation of each command in the program source code.

How to write Script in Selenium WebDriver

How to write automated test script in Java

1. Scenario to Automate:
1. Launch the Firefox browser by creating the WebDriver object.
2. Open website www.google.co.in using get() method.
3. Wait for the page to load.
4. Print a message to display on the console that website is opened successfully.
5. Close the browser.

Important steps to follow: 
1. To create your first Selenium WebDriver script, First, open your Eclipse IDE.
2. Create a Java Project. Go to File > New > Java Project and write "Selenium WebDriver Project". 
3. Create a Package. Go to src > Right click > New > Package and declare a name "practiceWebDriver".
4. Now create a Java class. Go to practiceWebDriver > Right click > New > Class and declare a class name "FirstSeleniumWebDriverScript".
Program source code: 1 
    package practiceWebdriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FirstSeleniumWebDriverScript { // To execute any program we need a main() method. So we will continue from the main method. public static void main(String[] args) { // First create web driver object and launch the Firefox browser. // Since WebDriver is an interface and Firefox driver is a class which implements all the methods of the web driver interface WebDriver driver=new FirefoxDriver(); // FirefoxDriver class with no parameters. i.e It will launch default Firefox by Java program. Default Firefox profile is similar to launching the firefox in safe mode. // Declaration of variable URL with datatype String and store the URL of the webpage. String URL="https://www.google.co.in"; // Now call the get() command to open the URL of the webpage. driver.get(URL); // It takes String URL as a parameter and returns nothing. // Wait For Page To Load driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); // Print a message to display on the console that the website is opened successfully. System.out.println("Website is opened successfully"); // Now call the close() method using reference variable 'driver' to close the browser. driver.close(); } }
    Output: Website is opened successfully.
Explaining the code
➲ When you will write the statement "WebDriver driver=new FirefoxDriver();" in your script, you will notice that there are two errors underlined with the red color line at the statement in the code.
Selenium example programs in Java

➲ This underlined red colored word represents the error in the Eclipse IDE. Since the Eclipse IDE is a powerful tool and a lot of very wonderful features. Therefore, It will give you to use the best feature like "Solution suggestion". 
➲ To use this feature, you just bring the mouse cursor on the first redline error keyword "WebDriver" and then second redline keyword "FirefoxDriver".  Eclipse will automatically show you the best solutions to fix the error.
➲ This suggestion will work only when you have added the selenium WebDriver jars to your project otherwise, Eclipse will not show suggestions of the correct solution to fix the errors.
➲ As you bring the mouse cursor to the error, Eclipse will show you different solutions but you have to select the first solution provided by the eclipse. After selecting the first solution, Eclipse IDE will import two import statements "import org.openqa.selenium.WebDriver;" and "import org.openqa.selenium.firefox.FirefoxDriver;" at the top of the coding script. After importing, the error will be gone.

Importing Packages 
org.openqa.selenium.WebDriver: It contains the WebDriver class to instantiate a new browser loaded with a specific driver. 
org.openqa.selenium.firefox.FirefoxDriver: It contains the FirefoxDriver class to instantiate a Firefox driver onto the browser instantiated by the web driver class.

Running the Java Test Case 
After resolving all errors, You have to execute the code of your first automated test case in the Eclipse IDE. There are two ways to execute the test case.
1. On Eclipse's menu bar, click Run > Run As > Java Application or Right click on the eclipse code, click Run As > Java Application.
2. Press Ctrl+F11 to run the entire code.
After a few seconds, a Firefox browser will open and Selenium will launch the Google page with the help of your script. After launching completely, the browser will be closed after waiting a few seconds. Once the execution is finished, a message "Website is opened successfully" will display on the console section of the Eclipse IDE.
Let's see one more example program to understand the concepts.

2. Scenario to Automate:
1. Launch the Firefox browser.
2. Open website www.google.com using get() method.
3. Wait for the page to load completely using an implicit wait.
4. Get the actual title of the page.
5. Print the actual title of the page.
6. Compare the actual title of the page with the expected title.
7. Get the current URL of the page.
8. Print the current URL of the page.
9. Get the title length of the page and print it.
10. Now close the browser.
Program source code 2:
    package practiceWebdriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Practice { public static void main(String[] args) { // Create the driver object to launch the Firefox browser. WebDriver driver=new FirefoxDriver(); // Declaration of variable URL with datatype String and stores the URL of the webpage. String URL="http://www.google.com"; // Now call the get() command to open the URL of the webpage. driver.get(URL); // It takes parameter URL as a String and returns nothing. // Wait for Page to load completely. driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS ); // Get the actual title of the page. // Call the getTitle() method to get the actual title of the page. Since the return type of the getTitle() method is a String. Therefore, we will store it using a variable ActualTitle with DataType String. String ActualTitle=driver.getTitle(); // It takes nothing as parameter. If the page has no title, it will return null string. System.out.println("Actual title of the Webpage: " +ActualTitle); // Compare the actual title of the page with expected. // We will store the Expected title using a variable ExpectedTitle with Datatype String. String ExpectedTitle="Google"; // Use if statement and equals() method. if(ActualTitle.equals(ExpectedTitle)){ System.out.println("Test passed"); } else { System.out.println("Test failed"); } // Get the current URL of the page. String getCurrentURL=driver.getCurrentUrl(); // Return type is String. System.out.println("Current URL of the page: " +getCurrentURL); // Get the title length of the page. Since the return type is Integer. Therefore, We will store it using a variable TitleLength with Datatype int. int TitleLength = driver.getTitle().length(); // Printing Title length System.out.println("Length of the Title: " + TitleLength); // Close the browser. driver.close(); // It takes nothing as a parameter and returns nothing. }}
    Output: Actual title of the Webpage: Google Test passed Current URL of the page: https://www.google.com/?gws_rd=ssl Length of the Title: 6
To run and execute the test case, follow all the above steps.

3. Scenario to Automate:
1. Launch the Firefox browser.
2. Open website www.google.com using navigate().to() method.
3. Wait for the page to load completely using an implicit wait.
4. Click on the Gmail.
5. Get the actual title of the page and print it.
6. Move back by one page on the browser's history.
7. Use sleep() method in a try-catch block to pause the execution.
8. Get the title of the page and print it.
9. Move forward by one page on the browser's history.
10. Get and print the title and current URL of the webpage.
11. Refresh the current page.
12. Get the length of the title of the page.
13. Now close the browser.

Program source code 3:
    package practiceWebdriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class NavigationCommandExample { public static void main(String[] args) { // Create the driver object to launch the Firefox browser. WebDriver driver=new FirefoxDriver(); // Declaration of variable URL with datatype String and stores the URL of the webpage. String URL="http://www.google.com"; // Now call the navigate().to() command to open the URL of the webpage. driver.navigate().to(URL); // It takes parameter URL as a String and returns nothing. // Wait for Page to load completely. driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS ); // Click on Gmail. // Call the findElement method using object reference variable 'driver'. WebElement element=driver.findElement(By.linkText("Gmail")); // The return type of findElement method is WebElement. element.click(); String titlePage=driver.getTitle(); System.out.println("Title of the Webpage: " +titlePage); // Move to the previous webpage. // Call navigate().back() command to move back by one page on the browser's history. driver.navigate().back(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } String titlePage2 = driver.getTitle(); // Print the title text of the previous webpage System.out.println("Title of the previous page is : " + titlePage2); // Move to the next webpage. // Call the navigate().forward() command to move forward by one page on the browser's history. driver.navigate().forward(); // It takes nothing as parameter and returns nothing. String forwardTitlePage=driver.getTitle(); System.out.println("Title of forward webpage: " +forwardTitlePage); String currentURL=driver.getCurrentUrl(); System.out.println("URL of the current page: " +currentURL); // Refresh the current webpage. // Call navigate().refresh() command to refresh the current page. driver.navigate().refresh(); // accepts nothing as a parameter and returns nothing. String getTitle=driver.getTitle(); int titleLength=getTitle.length(); // Return type of the length() method is an integer. // The above two lines of code can also be written in one step like this. // int titleLength=driver.getTitle().length(); System.out.println("Length of the title: " +titleLength); // Close the browser. driver.close(); // It takes nothing as a parameter and returns nothing. } }
    Output: Title of the Webpage: Gmail - Free Storage and Email from Google Title of the previous page: Google Title of forward webpage: Gmail - Free Storage and Email from Google URL of the current page: https://www.google.com/intl/en-GB/gmail/about/ Length of the title: 42
Final words 
We hope that this article will help you to learn how to write test script in Selenium WebDriver. All the programs are very basic but important to understand and clear the concepts of each command. So, practice them.