Create your first WebDriver script

Before reading this post, first you have to setup a JAVA project in your eclipse where you can copy the script explained below and see the actual execution of it. I have already explained the project setup steps in my previous post. If you miss that post, click here.

Lets create a very basic script in webdriver that would perform following actions :-
a) Launch google.com page in Firefox Browser
b) Fetch the title of it
c) Verify its title
d) print the comparison result in Eclipse Console
e) Close browser

First create a new class in a JAVA project where you have to write the Selenium Webdriver code to automate above mentioned scenario.

Create a new class in a project
Once you create a project in Eclipse, you will see a folder called ‘src’ in it. Right click on ‘src’ folder, select ‘New’ and then click on ‘class’.

FirstScript1

It will open a popup, where you have to input required details like Class Name, Package Name etc. Once you done with details, click on ‘Finish’ button.

FirstScript2

A newly created class will look like :-

FirstScript3

Now, Just copy the below code in your newly create class.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class Sample {
  
  public static void main(String s[]) {
        String baseUrl = "http://www.google.com";
        String expectedPageTitle = "Google";
        String actualPageTitle = "";
  
        //Initialize driver object
        WebDriver driver = new FirefoxDriver();
	  
        //Launch Application on browser
        driver.get(baseUrl);
	  
        //Fetch page title and store it in a variable
        actualPageTitle = driver.getTitle();
        //Print title
        System.out.println(actualPageTitle);
	  
        if (actualPageTitle.equals(expectedPageTitle)) {
             System.out.println("Test case passed");
         } else {
	     System.out.println("Test case Failed");
         }
	  
         //close browser
         driver.close();   
  }
 
}

In order execute above script, just right click on Java file > Run As > Java Application. Kindly refer below screen shot in case you have any confusion.

FirstScript

As soon as you click on ‘Java Application’ option, the execution will be started and code output would be printed in Console.

FirstScript

If you really like the information provided above, please don’t forget to like us on Facebook, you can also leave the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *