Monday, 5 September 2016

Selenium Webdriver - C# with NUNIT 3 using visual studio

Step1:  Open Visual studio
Step2: Choose Extension and updates from Tools Menu
Step3: Install 'NUnit 3 Test Adapter' and 'NUnit Template fro Visual Studio' - Follow below screen:

Step4: Create new Project from File-> New Project -> Test -> NUnit 3 Unit test Project:  Follow below screen

Step5: Double Click on CS File from View- > Solution Exploer

Step6: Install Selenium Webdriver, Webdriver support and chromedriver dlls by right clicking on Solution and choosing manage Nuget Package
Step 7: Install above DLLS , please follow below screen:

Step8:  Replace the code of CS file with below codes .

using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace NUnit.Tests
{
    [TestFixture]
    public class TestClass
    {
        public static IWebDriver driver;

        [Test]
        public void TestMethod()
        {
            //To Launch Firefox
            driver = new FirefoxDriver();

            //To Navigate Given URL
            driver.Navigate().GoToUrl("http://newtours.demoaut.com");

            //Implicitly wait for 30 seconds
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));
            //Enter credentials and login
            driver.FindElement(By.Name("userName")).SendKeys("mercury");
            driver.FindElement(By.Name("password")).SendKeys("mercury");
            driver.FindElement(By.Name("login")).Click();
        }
    }
}


Step8: Run Test from  Test -> Run-> All Tests menu

Friday, 18 September 2015

TestNG + Selenium WebDriver configuration and execution


Install TestNG
1.        Launch the Eclipse IDE
2.       Navigate to Help->Install new software
3.       In Install dialog window, click “Add” button.
4.       Type name as you wish, for example :- “TestNG”
5.       Type “http://beust.com/eclipse/” as location.
6.       Click OK.
7.        Just Click TestNG checkbox
8.       Press “Next” button.
9.       Click “I accept the terms of the license agreement”
10.   Click Finish.
11.   Restart Eclipse

Create testng Class
1.       Right click on your package ( for this example package is p1)
2.       Select New-> Others->testing class
3.       Enter name of the class ( for this example name is testng1)
4.       Click OK
5.       Copy paste below code in the opened class

package p1;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class testng1 {
      
       WebDriver driver;
      
  @Test(groups = {"Regression"},priority = 2)
  @Parameters({"Browser1","url1"})
  public void test1(String sBrowser,String url) {
        
         if (sBrowser.equalsIgnoreCase("firefox"))
         {
                driver=new FirefoxDriver();
         }
         else if (sBrowser.equalsIgnoreCase("ie"))
         {
                System.setProperty("webdriver.ie.driver", "C:/imp/software/IEDriverServer.exe");
                driver=new InternetExplorerDriver();
         }
        
         else
         {
                System.out.println("Invalid browser");
                System.exit(0);
         }
        
         driver.get(url);
         String sTitle=driver.getTitle();
         System.out.println("Title is "+ sTitle);
         Assert.assertEquals("idojfioe", sTitle);
         driver.close();
  }
 
  @Test(groups = {"Smoketest"},priority = 1)
  @Parameters({"Browser2","url2"})
  public void test2(String sBrowser,String url) {
        
         if (sBrowser.equalsIgnoreCase("firefox"))
         {
                driver=new FirefoxDriver();
         }
         else if (sBrowser.equalsIgnoreCase("ie"))
         {
                System.setProperty("webdriver.ie.driver", "C:/imp/software/IEDriverServer.exe");
                driver=new InternetExplorerDriver();
         }
        
         else
         {
                System.out.println("Invalid browser");
                System.exit(0);
         }
        
         driver.get(url);
         String sTitle=driver.getTitle();
         System.out.println("Title is "+ sTitle);
         driver.close();
  }
}

Create TestNG xml file
1.       Right click on your Project
2.       Select New-> File
3.       Enter name of the file ( for this example name is testing.xml)
4.       Click OK
5.       Copy paste below code in xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite" parallel="false">
                <parameter name="Browser1" value="firefox"/>
                <parameter name="Browser2" value="ie" />
                <parameter name="url1" value="http://www.google.com"/>
                <parameter name="url2" value="http://newtours.demoaut.com" />
                <test name="Selenium-AutomationSuite">
                                <groups>
                                                <run>
                                                                  <include name="Smoketest" />
                                  <include name="Regression" />
                                                </run>
                                </groups>
                                <classes>
                                                 <class name="p1.testng1"/>
                                                 
                                                 
                                               
                                </classes>
                </test>
</suite>

Run the Suite
1.       Right click on xml file(testing.xml)
2.       Navigate to Run as-> TestNG Suite



Friday, 17 July 2015

Selenium Web driver integration with HP-ALM

As selenium is open source and not having any inbuilt integration with any test management tool. It is very important and handy to integrate selenium with well-established test management tool (HP-ALM)

Steps:

     1. Register 'OTAClient.dll' with registry
a.     open command prompt by typing cmd in run command
b.     copy below command and press enter

         regsvr32  ” complete path of OTAClient.dll file in your local system”
           ex:  regsvr32  "C:\Users\user1\AppData\Local\HP\ALM-Client\10\OTAClient.dll"

2.   Convert the DLL file into Jar
c.      Download ‘com4j.jar file’, downloaded file will be in zip format, extract the zip file in some folder.
d.     Navigate to extracted folder in command prompt
e.     Enter the below command
java -jar tlbimp.jar -o alm -p com.qc ” complete path of OTAClient.dll file in your local system”
f.       All java files will be available in alm folder under parent folder( where you extracted the zip file)

3.   Export these java files as jar filefrom eclipse.
g.     Copy com folder ,created under  alm folder , and copy it in src folder of eclipse
h.     You will get com.qc and com.qc.events folder in created under src folder in eclipse
i.        Select the folder and export as jar file, save as ‘otaclient.jar’
Add these two jar files (‘com4j.jar’ and ‘otaclient.jar’) and you are good to go with ALM-integrated selenium run.

Tuesday, 10 March 2015

Selecting item from ListBox and check which value is selected

import org.openqa.selenium.*;

import org.openqa.selenium.firefox.*;
import org.openqa.selenium.support.ui.Select;


// - Selecting Existing list of values from ListBox
// and check which value is selected
public class WebDriver19 {

/**
* @param args
*/
public static WebDriver oBrowser;
public static String sUrl = "http://www.goibibo.com";
public static void main(String[] args)
{
boolean bIsBrowserOpened;

bIsBrowserOpened = OpenBrowser();

if (bIsBrowserOpened)
{
Set_ListBox_Item_Method3();
//Set_ListBox_Item_Method2_Valid();
//Set_ListBox_Item_Method2_InValid();
CloseBrowser();
}


}

public static boolean OpenBrowser()
{
try
{
oBrowser = new FirefoxDriver();
oBrowser.get(sUrl);
try
{
Thread.sleep(5000L);
}
catch (Exception e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
return false;
}
return true;

}



public static void CloseBrowser()
{
oBrowser.close();
}

public static void Set_ListBox_Item_Method1()
{
WebElement oListBox;


oListBox = oBrowser.findElement(By.id("gi_source"));
oListBox.sendKeys("Hyderabad");

}

//For throwing not found exception
public static void Set_ListBox_Item_Method2_Valid()
{
WebElement oListBox;


oListBox = oBrowser.findElement(By.id("gi_source"));
//oListBox.sendKeys("Hyderabad");
try
{


oListBox.findElement(By.xpath("//option[@value='HYD']")).click();

}
catch(NoSuchElementException e)
{
System.out.println("Specified Item Not Found");
}
catch(Exception e)
{
e.printStackTrace();
}
}

public static void Set_ListBox_Item_Method2_InValid()
{
WebElement oListBox;

oListBox = oBrowser.findElement(By.id("gi_source"));

//oListBox.sendKeys("Hyderabad");
try
{


oListBox.findElement(By.xpath("//option[@value='HYD123']")).click();

}
catch(NoSuchElementException e)
{
System.out.println("Specified Item Not Found");
}
catch(Exception e)
{
e.printStackTrace();
}
}

public static void Set_ListBox_Item_Method3()
{ //using select class
WebElement oListBox;
Select ListSelect;
oListBox = oBrowser.findElement(By.id("gi_source"));
ListSelect=new Select(oListBox);
ListSelect.selectByValue("HYD");
System.out.println("Selected:= "+ListSelect.getAllSelectedOptions().get(0).getText());
ListSelect.selectByVisibleText("Pune");
System.out.println("Selected:= "+ListSelect.getAllSelectedOptions().get(0).getText());

}

}

Monday, 28 October 2013

Getting count of Different Web Element displayed in the page using WebDriver

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

//Getting count of Different Web Element  displayed
public class WebDriverElementCount {

public static WebDriver oBrowser;
public static String sUrl="http://in.yahoo.com";
public static void main(String[] args)
{
boolean bIsBrowserOpened;

bIsBrowserOpened=OpenBrowser();
if(bIsBrowserOpened)
{

Display_Element_Count();
CloseBrowser();
}

}
public static boolean OpenBrowser()
{
try
{
oBrowser=new FirefoxDriver();
oBrowser.get(sUrl);
try
{
Thread.sleep(5000L);
}
catch(Exception e)
{
e.printStackTrace();
}
return true;
}
catch(Exception e)
{
System.err.println(e.getMessage());
return false;
}
}

public static void Display_Element_Count()
{
Get_Element_Count("Link","//a");
Get_Element_Count("Image","//img");
Get_Element_Count("TextBox","//input[@type='text']");
Get_Element_Count("Form Submit Button","//input[@type='submit' or @type='clear']");
Get_Element_Count("HTML 4/5 button","//button");
Get_Element_Count("Radio Button","//input[@type='radio']");
Get_Element_Count("CheckBox","//input[@type='checkbox']");
Get_Element_Count("List Box","//select");
Get_Element_Count("Activex Button","//object");
Get_Element_Count("Text Area","//textarea");
}
public static void Get_Element_Count( String sElementName,String sXpath_of_Element)
{
int iCount;
if(!sXpath_of_Element.isEmpty())
{
iCount=oBrowser.findElements(By.xpath(sXpath_of_Element)).size();
System.out.printf("\n No of (%s)  Element= %d" ,
sElementName,iCount);
}
}
public static void CloseBrowser()
{
oBrowser.close();
}

}


Reading Existing list of values from ListBox Using WebDriver

import java.util.List;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;

// - Reading Existing list of values from ListBox
public class WebDriver18 {
/**
* @param args
*/
public static WebDriver oBrowser;
public static String sUrl = "http://www.goibibo.com";
public static void main(String[] args)
{
boolean bIsBrowserOpened;
bIsBrowserOpened = OpenBrowser();
if (bIsBrowserOpened)
{
Get_ListBox_Items();
CloseBrowser();
}
}
public static boolean OpenBrowser()
{
try
{
oBrowser = new FirefoxDriver();
oBrowser.get(sUrl);
try
{
Thread.sleep(5000L);
}
catch (Exception e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
return false;
}
return true;
}

public static void CloseBrowser()
{
oBrowser.close();
}
public static void Get_ListBox_Items()
{
WebElement oListBox;
int iElement, iCount;
List<WebElement> oAllListValues;
oListBox = oBrowser.findElement(By.id("gi_source"));
oAllListValues = oListBox.findElements(By.tagName("option"));
iCount = oAllListValues.size();
System.out.println("No of Items found in list box ="+String.valueOf(iCount));
System.out.println("*********************************");
for (iElement=0; iElement<iCount; iElement++)
{
System.out.printf("\n Item (%d/%d) = %s",
iElement+1,iCount,
oAllListValues.get(iElement).getText());
}

}

}

Wednesday, 6 February 2013

WebDriver with JUNIT


import java.util.concurrent.TimeUnit;

import junit.framework.Assert;

import  org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class WebDriverJunit {

public static WebDriver oBrowser;

@BeforeClass
public static void Selenium_init()
{
oBrowser=new FirefoxDriver();
oBrowser.manage().window().maximize();
oBrowser.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
oBrowser.get("http://www.bing.com");
}

@AfterClass
public static void Selenium_End()
{
oBrowser.quit();
}

@Test
public void Validate_Edit()
{
WebElement oEdit;

try
{
oEdit=oBrowser.findElement(By.id("sb_form_q"));
Assert.assertEquals("", oEdit.getText());
}
catch(Exception e)
{
Assert.fail(e.getMessage());
}
}

@Test
public void Search()
{
WebElement oEdit,oButton;
String sPageSource;

try
{
oEdit=oBrowser.findElement(By.id("sb_form_q"));
oButton=oBrowser.findElement(By.id("sb_form_go"));
oEdit.sendKeys("Selenium");
oButton.click();
sPageSource=oBrowser.getPageSource();
oBrowser.navigate().back();
if (sPageSource.lastIndexOf("Selenium")<100)
{
Assert.fail("No Proper result");
}
}
catch(Exception e)
{
Assert.fail(e.getMessage());
}
}
}

Sunday, 13 January 2013

Detecting no.of popups , Fetching their titles and closing popups using webdriver

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;

// ---- Detecting no.of popups and fetching
//      their titles and closing popups
// ---- closing all parent and child window with .quit() method.

public class WebDriverPopupDemo {

    /**
     * @param args
     */
    public static WebDriver oBrowser;
    public static String sUrl = "http://naukri.com";
// --- Reading existing text from TextBox
    public static void main(String[] args)
    {
        boolean bIsBrowserOpened;
       
        bIsBrowserOpened = OpenBrowser();
       
        if (bIsBrowserOpened)
        {
           
            Get_Popup_Count();
            Get_Popup_Title();
            Closing_Popups();
            CloseBrowser();   
        }
       
   
    }
   
    public static boolean OpenBrowser()
    {
        try
        {
            oBrowser = new FirefoxDriver();
            oBrowser.get(sUrl);
            try
                {
                    Thread.sleep(5000L);
                }
            catch (Exception e)
                {
                    e.printStackTrace();
                }
        }
        catch (Exception e)
        {
            System.err.println(e.getMessage());
            return false;
        }
        return true;
       
    }
   
    public static void Get_BrowserInfo()
    {
        String sTitle, sSource;
        sTitle = oBrowser.getTitle();
        sSource = oBrowser.getPageSource();
        System.out.println("Page Title ="+sTitle);
        System.out.println("******");
        System.out.println("Page Source....");
        System.out.println(sSource);
    }
   
    public static void CloseBrowser()
    {
        // oBrowser.close(); // --- closes only parent
       
        oBrowser.quit(); // --- closes all, including popups..
    }
   
    public static void Get_Popup_Count()
    {
        int iPopupCount;
       
        iPopupCount = oBrowser.getWindowHandles().size();
       
        if (iPopupCount == 1)
        {
            System.out.println("Only! parent window & no popups");
           
        }
        else
        {
        System.out.println("parent and popup both exist");   
        System.out.println("Total No of Windows = "+iPopupCount);
       
        }
    }
   
    public static void Get_Popup_Title()
    {
        int iPopupCount, iPopup;
        Object[] lsAllHandles;
        String sWindowTitle;
       
        lsAllHandles = oBrowser.getWindowHandles().toArray();
       
        iPopupCount = lsAllHandles.length;
       
        for (iPopup=0; iPopup<iPopupCount; iPopup++)
        {
            sWindowTitle = oBrowser.switchTo().window((String) lsAllHandles[iPopup]).getTitle().toString();
           
            if (iPopup==0)
            {
            System.out.printf("\n Main window title = %s",
                    sWindowTitle);
            }
            else
                System.out.printf("\n window (%d of %d) = %s",
                        iPopup, iPopupCount-1,sWindowTitle);
        }
       
       
    }
   
    public static void Closing_Popups()
    {
        int iPopupCount, iPopup;
        Object[] lsAllHandles;
        String sWindowTitle;
       
        lsAllHandles = oBrowser.getWindowHandles().toArray();
       
        iPopupCount = lsAllHandles.length;
       
        if (iPopupCount>0) // -- there are popups
        {
       
            for (iPopup=1; iPopup<iPopupCount; iPopup++)
            {
                sWindowTitle = oBrowser.switchTo().window((String) lsAllHandles[iPopup]).getTitle().toString();
               
                System.out.printf("\n Closing Pop Window (%d of %d)=%s",
                        iPopup,iPopupCount-1,sWindowTitle);
                oBrowser.switchTo().window((String)lsAllHandles[iPopup]).close();
            }
            oBrowser=oBrowser.switchTo().window((String)lsAllHandles[0]);
        }
       
       
    }
   
   

}

Simple Webdriver program to open Browser,print browser info and close Browser

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;


public class WebDriverDemo {


    public static WebDriver oBrowser;
    public static String sUrl="http://www.bing.com";
       
   
    public static void main(String[] args)
    {   
        boolean bIsBrowserOpened;
       
        bIsBrowserOpened=OpenBrowser();
        if(bIsBrowserOpened)
        {
            Get_BrowserInfo();
            CloseBrowser();
        }
       
    }
    public static boolean OpenBrowser()
    {
        try
        {
            oBrowser=new FirefoxDriver();
            oBrowser.get(sUrl);
            try
            {
                Thread.sleep(5000L);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            return true;
        }
        catch(Exception e)
        {
            System.err.println(e.getMessage());
            return false;
        }
    }
   
    public static void Get_BrowserInfo()
    {
        String sTitle,sSource;
        sTitle=oBrowser.getTitle();
        sSource=oBrowser.getPageSource();
        System.out.println("Page Title =" + sTitle);
        System.out.println("****************************************");
        System.out.println("Page Source.......");
        System.out.println(sSource);
       
       
    }
   
    public static void CloseBrowser()
    {
        oBrowser.close();
    }
   
}