Creating your first selenium script

Let's create first test script in Selenium webdriver.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class test{

 public static void main(String[] args){

  System.setProperty("webdriver.gecko.driver","./lib/geckodriver.exe");

  WebDriver driver = new FirefoxDriver();
  driver.get("http://google.com");
  String Title = driver.getTitle();

  // compare the actual title of the page with the expected one
  if (Title.contentEquals("Google")) {
   System.out.println("Test Passed!");
  } else{
   System.out.println("Test Failed");
  }
  driver.close();
 }
}

Explanation:

1) Import packages:
You have to import following packages at start:

org.openqa.selenium.*  -> contains the WebDriver class needed to instantiate a new browser loaded with a specific driver.

org.openqa.selenium.firefox.FirefoxDriver  -> contains the FirefoxDriver class needed to instantiate a Firefox-specific driver onto the browser instantiated by the WebDriver class.

You will need to import more packages when you will develop your script more complex.

2) To instantiate driver object:
Setting GeckoDriver path on windows for Selenium WebDriver. Download gecko driver from here
 System.setProperty("webdriver.gecko.driver","<<Path of gecko driver>>");
 WebDriver driver = new FirefoxDriver();

3) Launch a browser:
We will use webdriver's get() method to launch a new browser session and directs it to the specified URL.
driver.get("http://google.com");

4) Get the actual page title:
The webdriver class has the getTitle() method that is used to get the page title of the current page.
driver.getTitle();

5) Compare the expected and actual values:
The following code is use to compare the actual title with the expected one.

if (Title.contentEquals("Google")){

           System.out.println("Test Passed!");
       } else {
           System.out.println("Test Failed");
  }

6) Terminating a browser session:
The "close()" method is used to close the browser window.

7) Running the test in eclipse:
On Eclipse's menu bar, click Run --> Run
OR
Press Ctrl+F11 to run the entire code.

Output :- Test Passed!



<-- Previous || Next -->

1 comment:

  1. You are doing a good job and sharing your knowledge to others! it was one of the good post to read and useful to improve the knowledge as updated one, keep doing the good work.

    Selenium Training in Electronic City, Bangalore my knowledge as updated one, keep blogging.

    ReplyDelete