About Me

Page views

Powered by Blogger.

Followers

Friday 22 May 2015


So How to get any text is available in HTML Page Source Code using Selenium WebDriver.


Steps :
  1.  Define Firefox Browser and open the Firefox Browser
  2.  Open the URL (Website)
  3.  Identify the number of Links on webpage and assign into Webelement List
  4. Count the total Link list on Web Page 
  5. Print the total count of links on webpage
  6. Identify all the elements on web page
  7. Count the total all element on web page
  8. Print the total count of all element on webpage
  9. Print all the Tag Name and Text Name on webpage.

Practice Yourself :

package dayOne;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Count_Total_Weblink_and_AllElement_on_Webpage {

       public static void main(String[] args) {
             
              //Define the Webdriver for Browser i.e. Firefox
              WebDriver driver = new FirefoxDriver();
               
              //Open the URL (Website)
        driver.get("http://yahoo.com");
       
        //Identify the number of Link on webpage and assign into Webelement List 
        List<WebElement> allLinkElements = driver.findElements(By.xpath("//a"));
       
        // Count the total Link list on Web Page 
        int linkListCount = allLinkElements.size();
               
        //Print the total count of links on webpage
        System.out.println("Total Number of link count on webpage = "  + linkListCount);    
             
       //Identify all the elements on web page
       List<WebElement> allElements = driver.findElements(By.xpath("//*"));
      
       //Count the total all element on web page
       linkListCount = allElements.size();
    
       //Print the total count of all element on webpage
       System.out.println("Total Number of All Element on webpage = "  + linkListCount);   
      
       //Print all the Tag Name and Text Name on webpage
       int i = 0;
        for (WebElement Element : allElements) {
            i = i +1;
            System.out.println(Element.getTagName());
            System.out.println(Element.getText());
        }
        
        //Close the Broswer
       driver.close();
      
       // Quit the selenium
       driver.quit();
       
       }
}

Sunday 17 May 2015

So how to handle javascript alerts, confirmation and prompts?


JavaScript popups are generated by web application and hence they can be easily controlled by the browser.
Webdriver offers the ability to cope with javascript alerts using Alerts API
// Get a handle to the open alert, prompt or confirmation
Alert alert = driver.switchTo().alert();
Alert is an interface. There below are the methods that are used
//Will Click on OK button.
alert.accept();
// Will click on Cancel button.
alert.dismiss()
//will get the text which is present on th Alert.
alert.getText();
//Will pass the text to the prompt popup
alert.sendkeys();
//Is used to Authenticate by passing the credentials
alert.authenticateUsing(Credentials credentials)

This program will demonstrate you working on Alerts popup using above html file.

Saturday 9 May 2015



Creation of Sample TestNG project
Let us begin with the creation of TestNG project in eclipse IDE.
Step 1: Click on the File option within the menu -> Click on New -> Select Java Project.
Selenium TestNG tutorial 8
Step 2: Enter the project name as “DemoTestNG” and click on “Next” button. As a concluding step, click on the “Finish” button and your Java project is ready.
Selenium TestNG tutorial 9
Step 3: The next step is to configure the TestNG library into the newly created Java project. For the same, Click on the “Libraries” tab under Configure Build Path. Click on “Add library” as shown below.
Selenium TestNG tutorial 10
Step 4: The user would be subjected with a dialog box promoting him/her to select the library to be configured. Select TestNG and click on the “Next” button as shown below in the image. In the end, click on the “Finish” button.
Selenium TestNG tutorial 11
The TestNG is now added to the Java project and the required libraries can be seen in the package explorer upon expanding the project.
Selenium TestNG tutorial 12
Add all the downloaded Selenium libraries and jars in the project’s build path as illustrated in the previous tutorial.

Creating TestNG class

Now that we have done all the basic setup to get started with the test script creation using TestNG. Let’s create a sample script using TestNG.
Step 1: Expand the “DemoTestNG” project and traverse to “src” folder. Right click on the “src”package and navigate to New -> Other..
Selenium TestNG tutorial 13
Step 2: Expand TestNG option and select “TestNG” class option and click on the “Next” button.
Selenium TestNG tutorial 14
Step 3: Furnish the required details as following. Specify the Source folder, package name and the TestNG class name and click on the Finish button. As it is evident from the below picture, user can also check various TestNG notations that would be reflected in the test class schema. TestNG annotations would be discussed later in this session.
Selenium TestNG tutorial 15
The above mentioned TestNG class would be created with the default schema.
Selenium TestNG tutorial 16
Now that we have created the basic foundation for the TestNG test script, let us now inject the actual test code. We are using the same code we used in the previous session.
Scenario:
  • Launch the browser and open “gmail.com”.
  • Verify the title of the page and print the verification result.
  • Enter the username and Password.
  • Click on the Sign in button.
  • Close the web browser.
Code:
1package TestNG;
2import org.openqa.selenium.By;
3import org.openqa.selenium.WebDriver;
4import org.openqa.selenium.WebElement;
5import org.openqa.selenium.firefox.FirefoxDriver;
6import org.testng.Assert;
7import org.testng.annotations.Test;
8
9public class DemoTestNG {
10       public WebDriver driver = new FirefoxDriver();
11       String appUrl = &quot;https://accounts.google.com&quot;;
12
13@Test
14public void gmailLogin() {
15             // launch the firefox browser and open the application url
16              driver.get(&quot;https://gmail.com&quot;);
17              
18// maximize the browser window
19              driver.manage().window().maximize();
20              
21// declare and initialize the variable to store the expected title of the webpage.
22              String expectedTitle = &quot; Sign in - Google Accounts &quot;;
23              
24// fetch the title of the web page and save it into a string variable
25              String actualTitle = driver.getTitle();
26              Assert.assertEquals(expectedTitle,actualTitle);
27              
28// enter a valid username in the email textbox
29              WebElement username = driver.findElement(By.id(&quot;Email&quot;));
30              username.clear();
31              username.sendKeys(&quot;TestSelenium&quot;);
32
33// enter a valid password in the password textbox
34              WebElement password = driver.findElement(By.id(&quot;Passwd&quot;));
35              password.clear();
36              password.sendKeys(&quot;password123&quot;);
37              
38// click on the Sign in button
39              WebElement SignInButton = driver.findElement(By.id(&quot;signIn&quot;));
40              SignInButton.click();
41              
42// close the web browser
43              driver.close();
44}
45}
Code Explanation with respect to TestNG
1) @Test – @Test is one of the TestNG annotations. This annotation lets the program execution to know that method annotated as @Test is a test method. To be able to use different TestNG annotations, we need to import the package “import org.testng.annotations.*”.
2) There is no need of main() method while creating test scripts using TestNG. The program execution is done on the basis of annotations.
3) In a statement, we used Assert class while comparing expected and the actual value. Assert class is used to perform various verifications. To be able to use different assertions, we are required to import “import org.testng.Assert”.

Executing the TestNG script

The TestNG test script can be executed in the following way:
=> Right click anywhere inside the class within the editor or the java class within the package explorer, select “Run As” option and click on the “TestNG Test”.
Selenium TestNG tutorial 17
TestNG result is displayed into two windows:
  • Console Window
  • TestNG Result Window
Refer the below screencasts for the result windows:
Selenium TestNG tutorial 18
(Click on image to view enlarged)
Selenium TestNG tutorial 19

HTML Reports

TestNG comes with a great capability of generating user readable and comprehensible HTML reports for the test executions. These reports can be viewed in any of the browser and it can also be viewed using Eclipse’s build –in browser support.

To generate the HTML report, follow the below steps:

Step 1: Execute the newly created TestNG class. Refresh the project containing the TestNG class by right clicking on it and selecting “Refresh” option.
Step 2: A folder named as “test-output” shall be generated in the project at the “src” folder level. Expand the “test-output” folder and open on the “emailable-report.html” file with the Eclipse browser. The HTML file displays the result of the recent execution.
Selenium TestNG tutorial 20
Selenium TestNG tutorial 21
Step 3: The HTML report shall be opened with in the eclipse environment. Refer the below image for the same.
Selenium TestNG tutorial 22
Refresh the page to see the results for fresh executions if any.

Setting Priority in TestNG

Code Snippet
1package TestNG;
2import org.testng.annotations.*;
3public class SettingPriority {
4
5@Test(priority=0)
6public void method1() {
7 }
8
9@Test(priority=1)
10public void method2() {
11 }
12
13@Test(priority=2)
14public void method3() {
15 }
16}



Following is the list of the most useful and favorable annotations in TestNG:
AnnotationDescription
@TestThe annotation notifies the system that the method annotated as @Test is a test method
@BeforeSuiteThe annotation notifies the system that the method annotated as @BeforeSuite must be executed before executing the tests in the entire suite
@AfterSuiteThe annotation notifies the system that the method annotated as @AfterSuite must be executed after executing the tests in the entire suite
@BeforeTestThe annotation notifies the system that the method annotated as @BeforeTest must be executed before executing any test method within the same test class
@AfterTestThe annotation notifies the system that the method annotated as @AfterTest must be executed after executing any test method within the same test class
@BeforeClassThe annotation notifies the system that the method annotated as @BeforeClass must be executed before executing the first test method within the same test class
@AfterClassThe annotation notifies the system that the method annotated as @AfterClass must be executed after executing the last test method within the same test class
@BeforeMethodThe annotation notifies the system that the method annotated as @BeforeMethod must be executed before executing any and every test method within the same test class
@AfterMethodThe annotation notifies the system that the method annotated as @AfterMethod must be executed after executing any and every test method within the same test class
@BeforeGroupsThe annotation notifies the system that the method annotated as @BeforeGroups is a configuration method that enlists a group and that must be executed before executing the first test method of the group
@AfterGroupsThe annotation notifies the system that the method annotated as @AfterGroups is a configuration method that enlists a group and that must be executed after executing the last test method of the group


TestNG is the framework which is very useful to use with selenium WebDriver.
The main reason behind TestNG's popularity is we can create and configure test case and test suite very easily using many different annotations of TestNG.

Annotations are those things in TestNG which guides it for what to do next or which method should be executed next. TestNG has also facility to pass parameters with annotations. Let we look at TestNG annotations list with its functional description.

@Test
@Test annotation describes method as a test method or part of your test.

@BeforeMethod
Any method which is marked with @BeforeMethod annotation will be executed before each and every @test annotated method.

@AfterMethod
Same as @BeforeMethod, If any method is annotated with @AfterMethod annotation then it will be executed after execution of each and every @test annotated method.


@BeforeClass
Method annotated using @BeforeClass will be executed before first @Test method execution. @BeforeClass annotated method will be executed once only per class so don't be confused. VIEWPRACTICALEXAMPLEOF@BeforeClass ANNOTATION

@AfterClass
Same as @BeforeClass, Method annotated with @AfterClass annotation will be executed once only per class after execution of all @Test annotated methods of that class. VIEWPRACTICALEXAMPLEOF@AfterClass ANNOTATION

@BeforeTest
@BeforeTest annotated method will be executed before the any @Test annotated method of those classes which are inside <test> tag in testng.xml file. VIEW PRACTICAL EXAMPLE

@AfterTest
@AfterTest annotated method will be executed when all @Test annotated methods completes its execution of those classes which are inside <test> tag in testng.xml file. VIEW PRACTICAL EXAMPLE

@BeforeSuite
Method marked with @BeforeSuite annotation will run before the all suites from test.

@AfterSuite
@AfterSuite annotated method will start running when execution of all tests executed from current test suite.

@DataProvider
When you use @DataProvider annotation for any method that means you are using that method as a data supplier. Configuration of @DataProvider annotated method must be like it always return Object[][] which we can use in @Test annotated method.
@BeforeGroups
@BeforeGroups annotated method will run before the first test run of that specific group.

@AfterGroups
@AfterGroups annotated method will run after all test methods of that group completes its execution.

@Parameters
When you wants to pass parameters in your test methods, you need to use @Parameters annotation. VIEWPRACTICALEXAMPLEOF@Parameters ANNOTATION

@Factory
When you wants to execute specific group of test cases with different values, you need to use @Factory annotation. An array of class objects is returned by @Factory annotated method and those TestNG will those objects as test classes.

@Listeners
@Listeners are used to with test class. It is helpful for logging purpose.

So How To Create And Run First TestNG-WebDriver Test Case In Eclipse ?

Step 1 : Create New Project And Package
Step 2 : Add TestNG Library
For adding TestNG library,
  • Go to your project's Properties -> Java Build Path -> Libraries Tab.
  • Click on Add Library button -> Select TestNG from Add Library popup and then click on Next and Finish buttons.

It will add TestNg library in your project as shown in bellow image. Now click on OK button to close that window.

Step 3 : Create TestNG Class
To add TestNg class
  • Right click on package "TestNGOnePack"  -> New -> Other. It will open New wizard window as bellow.
  • Select TestNg from New wizard window and click on Next button.
  • On next screen, add class name = ClassOne
  • It will add new class (ClassOne) under package as shown in bellow given image.
Step 4 : Add webdriver's external jar file in your project.
To Run webdriver test, you need to add webdriver's jar files as external jar file in your project. 

(Note : Do not add junit jar file as external jar file. Now its not required in TestNG framework).

This is it. Now you are ready to write your webdriver test script inside your class.

Step 5 : Add/write sample webdriver test script.
Write your own test script or add bellow given script in your class file.

package TestNGOnePack;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class ClassOne {
 
 WebDriver driver = new FirefoxDriver();
  
 //@BeforeMethod defines this method has to run before every @Test methods
 @BeforeMethod
 public void openbrowser() { 
  driver.manage().window().maximize();
  driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
 }

 //@AfterMethod defines this method has to run after every @Test methods
 @AfterMethod
 public void closebrowser() {
  System.out.print("\nBrowser close");
  driver.quit();
 }
 
 @Test
 public void testmethodone() {
   String title = driver.getTitle();
   System.out.print("Current page title is : "+title);
   System.out.print("\n'TestNGOne -> TestNGOnePack -> ClassOne -> testmethodone' has been executed successfully");
 }
}

Step 6 : Run Webdriver test script with TestNG

Go to Run -> Run As -> And Click on TestNg Test as shown in bellow given image.


It will run your webdriver test with TestNG. When execution completed, You will see result as shown in bellow given image.


Step 7 : View test execution HTML report generated by TestNG
To view test execution report,

  • Right click on "TestNGOne" project folder in eclipse and select Refresh.
  • Folder with name = "test-output" will be created under your project folder as shown in bellow given Image.
  • Explore that folder and open it with web Browser as shown in above image. It will open report in eclipse as shown in bellow given image.

Popular Posts

Copyright © Learn Selenium Yourself | Powered by Blogger
Design by Duan Zhiyan | Blogger Theme by NewBloggerThemes.com