Friday 25 November 2011

Different setup fixtures for different browsers in selenium webdriver using NUnit Framework

 public abstract class testwithMultiBrowser
    {
        protected IWebDriver driver;
        [Test]
        public void test()
        {
            driver.Navigate().GoToUrl("http://google.co.in");
        }
    }
  [TestFixture]
  class testwithFirefox:testwithMultiBrowser
    {
      [SetUp]
      public void firefoxSetup()
      {
          driver = new FirefoxDriver();
          IWindow window = driver.Manage().Window;
          window.Size = new Size(1366, 768);
      }
      [TearDown]
      public void tearDown()
      {
          driver.Quit();
      }
    }
    [TestFixture]
    class testwithIE:testwithMultiBrowser
    {
      [SetUp]
      public void iesetUP()
      {
          driver = new InternetExplorerDriver();
      }
      [TearDown]
      public void tearDown()
      {
          driver.Quit();
      }
 }

Thursday 24 November 2011

Run selenium test scripts in multiple browsers using NUnit Framework

[TestFixture(typeof(InternetExplorerDriver))]
[TestFixture(typeof(FirefoxDriver))]
public class testwithMultipleBrowsers<Testwebdriver> where Testwebdriver:IWebDriver ,new()
{
 IWebDriver driver;
 [SetUp]
 public void testsetup()
   {
    driver = new Testwebdriver(); 
    }
 [TearDown]
 public void teardownTest()
 {
  driver.Quit();
  }
  [Test]
  public void testMulitBrowser()
 {
  driver.Navigate().GoToUrl("http://google.co.in");
  driver.FindElement(By.Name("q")).SendKeys("testingtools");
  driver.FindElement(By.Name("btnG")).Click();
  }
}

Handling Ajax Autosuggests using selenium webdriver with CSharp

driver.Navigate().GoToUrl("http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AutoComplete/AutoComplete.aspx");
driver.FindElement(By.XPath("//input[contains(@id,'SampleContent_myTextBox')]")).SendKeys("test");
Thread.Sleep(TimeSpan.FromSeconds(2));
IWebElement element = driver.FindElement(By.XPath("//div[contains(@id,'master_contentplaceholder')]//div//ul"));
ReadOnlyCollection<IWebElement> texts=element.FindElements(By.TagName("li"));
IKeyboard key = ((IHasInputDevices)driver).Keyboard;
foreach(IWebElement text in texts)
{
  key.PressKey(Keys.ArrowDown);
  if (Equals("testMal", text.Text))
     {
        Console.WriteLine(text.Text);
        key.PressKey(Keys.Enter);
     }
     else
     {
        key.PressKey(Keys.ArrowDown);
        key.PressKey(Keys.Enter);
     }
  }

Wednesday 23 November 2011

Data Driven using Excel Data W/O oledb driver in selenium webdriver with CSharp

for (int i = 2; i <= 4; i++)
{
driver.Navigate().GoToUrl(baseURL);
driver.FindElement(By.LinkText("REGISTER")).Click();
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("D:\\Data.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
username = xlWorkSheet.get_Range("A" + i, "A" + i).Value2.ToString();
password = xlWorkSheet.get_Range("B" + i, "B" + i).Value2.ToString();xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
driver.FindElement(By.Name("email")).SendKeys(username);
driver.FindElement(By.Name("password")).SendKeys(password);
}

Data Driven using Excel Data with oledb connection in selenium webdriver with CSharp

string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "d:\\Userdata.xlsx" + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
 string selectusername = "SELECT *from [Sheet1$] ";
OleDbConnection con = new OleDbConnection(connectionstring);
OleDbCommand cmd = new OleDbCommand(selectusername, con);
con.Open();
OleDbDataReader thedata = cmd.ExecuteReader();
while (thedata.Read())
{
username = thedata[0].ToString();
password = thedata[1].ToString();
driver.Navigate().GoToUrl(baseURL);
driver.FindElement(By.LinkText("REGISTER")).Click();
driver.FindElement(By.Name("email")).SendKeys(username);
driver.FindElement(By.Name("password")).SendKeys(password);
driver.FindElement(By.Name("confirmPassword")).SendKeys(password);
}


Data Driven using SQL database in selenium webdriver with CSharp

driver.Navigate().GoToUrl(baseURL);
SqlCommand comm = new SqlCommand();
comm.Connection = new SqlConnection("Data Source=DANJANEYULU\\SQLEXPRESS;" + "Initial Catalog=Userdata; Trusted_Connection=Yes"); //Windows Authentication
string sql = @"select Username,Password from Userdata";
comm.CommandText = sql;
comm.Connection.Open();
SqlDataReader cursor = comm.ExecuteReader();
while (cursor.Read())
{
  string username=cursor["Username"].ToString();
  string password = cursor["Password"].ToString();
  driver.Navigate().GoToUrl(baseURL);
  driver.FindElement(By.LinkText("REGISTER")).Click();
  driver.FindElement(By.Name("email")).SendKeys(username);
  driver.FindElement(By.Name("password")).SendKeys(password);
  driver.FindElement(By.Name("confirmPassword")).SendKeys(password);
}
comm.Connection.Close();



Tuesday 22 November 2011

Connecting Remote System with Selenium webdriver using CSharp


Selenium standalone server should be run on the remote system.Then follow the procedure

namespace SeleniumFeatures
{
    [TestFixture]
    class SeleniumRemoteWebdriver
    {
        RemoteWebDriver driver;

        [SetUp]
        public void setupTest()
        {
driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"),  DesiredCapabilities.Firefox());   // Change the ip iddress to target remote system ip address
        }
        [Test]
        public void Test()
        {
            driver.Navigate().GoToUrl("http://google.co.in");
            driver.FindElement(By.Name("q")).SendKeys("testing tutorials");
            driver.FindElement(By.Name("btnG")).Click();

        }
    }
}

Extracting data from WebTable in selenium webdriver using csharp

driver.Navigate().GoToUrl("http://www.indiangoldrates.com/");
IWebElement table = driver.FindElement(By.XPath("//div[@id='post-7']//table[1]"));
ReadOnlyCollection<IWebElement> allRows = table.FindElements(By.TagName("tr"));
foreach (IWebElement row in allRows)
{
      ReadOnlyCollection<IWebElement> cells = row.FindElements(By.TagName("td"));
      foreach (IWebElement cell in cells)
      {
       Console.WriteLine("\t" + cell.Text);
      }
}

How to Handle drag and drop in selenium webdriver using CSharp

To do this we have to include using OpenQA.Selenium.Interactions name space

driver.Navigate().GoToUrl("http://developer.yahoo.com/yui/examples/dragdrop/dd-reorder.html");
IWebElement element = driver.FindElement(By.Id("li1_1"));
IWebElement target=driver.FindElement(By.Id("ul2"));
IWebElement target1 = driver.FindElement(By.Id("li2_1"));
new Actions(driver).DragAndDrop(element, target1).Build().Perform();
new Actions(driver).DragAndDropToOffset(target1, 75, 40).Build().Perform();

Monday 21 November 2011

Upload a file using selenium webdriver with CSharp


driver.Navigate().GoToUrl("http://www.freeonlinephotoeditor.com/");
IWebElement element=driver.FindElement(By.Id("file"));
element.SendKeys("d:\\anji.jpg");       //path of a file
driver.FindElement(By.Name("upload")).Click();

Moving a mouse on a Object and right clicking on it in Selenium Webdriver using CSharp



IWebElement element = driver.FindElement(By.XPath("//img[@name='jack']"));
new Actions(driver).MoveToElement(element).Perform();
ILocatable loc = (ILocatable)element;
IMouse mouse = ((IHasInputDevices)driver).Mouse;         // Converting driver as a Mouse
mouse.ContextClick(loc.Coordinates);                     //Right Click
IKeyboard key = ((IHasInputDevices)driver).Keyboard;    // Converting driver as a Keyboard
key.SendKeys("w");

How to handle DropDown list in selenium webdriver using Csharp

var selectCountry = driver.FindElement(By.Name("country")); // country is the name of the dropdown element
var selectedcountry = new SelectElement(selectCountry);  // Select element in dropdown
selectedcountry.SelectByText("INDIA ");           // Select value in list by using text. 

We can select values by using Index, value also

How to handle Prompts in selenium webdriver using CSharp

Here when we click on the below element it's asking for the name.

driver.FindElement(By.XPath("//input[@value='I dare you to click me!']")).Click();
IAlert alert = driver.SwitchTo().Alert();              //Switch to Alert
IWebElement name = driver.SwitchTo().ActiveElement();  // Switch driver to Active Element
name.SendKeys("anjaneyulu");
alert.Accept();
IAlert alert2 = driver.SwitchTo().Alert();
string text = alert2.Text;
Console.WriteLine(text);
alert2.Accept();

Handle Confirm Box in Selenium Webdriver Using Csharp

Here when we click on the below element on confirm box will appear with OK and Cancel buttons. After click on any of these two buttons another alert will open with OK button.

driver.FindElement(By.XPath("//div[@id='content']/table/tbody/tr[6]/td[3]/input")).Click();
IAlert alert = driver.SwitchTo().Alert();    // Switching to alert
string firstalert = alert.Text;              // Trying to get text from the alert
Console.WriteLine(firstalert);              // Display the text on Console
alert.Accept();                             // Click on OK Button
// alert.Dismiss();                         // Click on Cancel Button
IAlert alert1 = driver.SwitchTo().Alert();
string secondalert = alert1.Text;
Console.WriteLine(secondalert);
alert1.Accept();

Friday 18 November 2011

Working with Mouse Click in selenium webdriver using CSharp

In the below script , i am trying to click on image having name=jack.

Before to do this, we hav to include OpenQA.Selenium.Interactions  namespace  

IWebElement element = driver.FindElement(By.XPath("//img[@name='jack']"));
new Actions(driver).MoveToElement(element).Perform(); //Here i am moving driver to that element.
ILocatable loc = (ILocatable)element;       // Here i am getting co-ordinates of that element.
 IMouse mouse = ((IHasInputDevices)driver).Mouse; // Here i am converting driver as a mouse device.
 mouse.Click(loc.Coordinates);    //Here driver click on that coordinates.

Working with javascript popups in selenium webdriver using CSharp

driver.Navigate().GoToUrl("http://book.theautomatedtester.co.uk");
driver.FindElement(By.LinkText("Chapter1")).Click();
driver.FindElement(By.ClassName("multiplewindow")).Click();
driver.SwitchTo().Window("popupwindow"); // Here popupwindow is name of the window
string text = driver.FindElement(By.CssSelector("p[id='popuptext']")).Text;
Console.WriteLine(text);
driver.FindElement(By.CssSelector("p[id='closepopup']")).Click();
      
         

Tuesday 1 November 2011

Writing Selenium Tests in Eclipse


First we download Selenium IDE form http://seleniumhq.org/download/. It is a firefox plugin. Click on install
How to install Selenium IDE into your Browser.
Go to http://seleniumhq.org/docs/02_selenium_ide.html#installing-the-ide.
After Installation Selnium IDE will appear in Tools Menu

Click on Record Button on the Right Side corner OR Go to Action---> Click Record

Goto Url and Navigate some steps . After Navigation complete Stop Record.

Then we will get the script in Table format. If you want to source file click on source button. Default HTML code will appear.

If we want to write tests using java or csharp . Go to Options-->Format--->Select format --->Click OK.

If languages are not appear in the Format menu. Go to Options-->Options-->Select Enable Experimental Features. Now, we got the language options.

Copy the Entire code into your Class  Do the following changes in ur script.
1. Change Package name (i.e where our script appears.).  In the previouse example my script contains in com folde. So include this package like package com;
2. Change Untitled Class name to your Class name.
3. Click on Run. 

We will get the below after screenshot

If test passed Green Bar will appear otherwise Red Bar will appear. Don't forget to run selenium server before your test execution.

If you want ot run selenium tests using TestNG , instead of creating JUnit test case create TestNG Class.
Get the script by using TestNG (Remote Control) Format in Selenium IDE. Don't forget to add TestNG Jar file to your project.

Configuring Selenium RC with Eclipse using JUnit

Open Eclipse IDE
1. Select File-->New-->Java Project. Screen will be appear like below screenshot
Enter Project  Name and Click on Finish. On Left Side Bar we will get SeleniumRC Example in Package Explorer

2. Expand Project --> Right Click on Src--->New-->Folder --> enter folder name -->Click Finish
  Like in below screen shot.
3.In Project Explorer we found one package symbol with given folder name. Right Click on that -->New-->Junit Test Case --->Select JUnit3 or JUnit4 Test -->Enter Class name ---->Click Finish.
Like in below screen shot
Expand Package-->One file name with .java extension will appear and scren will be appear like
Right click on Java File-->Got Build Path--> Configur Build Path-->Select Libriaries-->Click on Add External JARs-->Browse for Selenium Source files-->Select Jar files in seleniu-server folder and select jar files present in Selenium Set-up-->Selenium java-client driver

Click OK.

Now Eclipse is Successsfully Configured with Selenium RC. We can write selenium tests in Eclipse

 If JUnit refernce files are not added to your project download JUnit jar file then Add this Jar file like above.

How to install TestNG Plugin in Eclipse

By using following steps we can easily install TestNG plugin in Eclipse

1. Go to Help--->Install Software
2. Click on Add button
3. One pop-up window opened with two text-fields :  Name and Location.
4. Enter TestNG for Name field  and Enter http://beust.com/eclipse/ into location field
5. Click OK .

Select check boxes and click finish. After Successfull installation, we will see the TestNG Test option in
Run Menu-->RunAs-->TestNG Test.







Calling Javascript in Selenium Webdriver

My requirement is to enter different usernames to test registration page. So, i want to generate random usernames by using java script.

Using Csharp

IJavaScriptExecutor js= driver as IJavaScriptExecutor;
string username=(string)js.ExecuteScript("return 'anji'+Math.floor(Math.random()*1111)");



Using Java

JavascriptExecutor js = (JavascriptExecutor) driver;
String username=(String)js.executeScript("return 'anji'+Math.floor(Math.random()*1111)");

We can pass this variable to username filed.










Thursday 27 October 2011

Writing tests using Selenium WebDriver

using System;
using System.Text;
using System.Threading;
using OpenQA.Selenium;
using NUnit.Framework;
using OpenQA.Selenium.IE;     // For IE include this name space
using OpenQA.Selenium.Support.UI;   //To setup execution speed include this name space
namespace SeleniumWebdriverExample
{
[TestFixture]
public class WebDriverExample
{
IWebDriver driver;

[SetUp]
public void SetupTest()
{
driver = new InternetExplorerDriver();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));  //Time in Seconds

}
[TearDown]
public void TeardownTest()
{
driver.Quit();
}
[Test]
public void TheUntitledTest()
{

driver.Navigate().GoToUrl("http://www.google.co.in/");
IWebElement query = driver.FindElement(By.Name("q"));    // Identifying by name
query.SendKeys("Cheese");                            // Type string into Textbox
IWebElement btnclick = driver.FindElement(By.Name("btnG"));
btnclick.Click();                                              // Button Click
}

}
}

Tuesday 25 October 2011

Different types for identifying elements in Selenium RC


selenium.Click("link=Images");                 // Identify  link by using label
selenium.WaitForPageToLoad("30000");       // wait for page to load
Assert.AreEqual("Google Images", selenium.GetTitle());
selenium.Click("css=#gb_8 > span.gbts");          //Identifying by using css selector
selenium.WaitForPageToLoad("30000");
Assert.AreEqual("Google Maps", selenium.GetTitle());      // Verifying by using page title
selenium.Click("link=News");
selenium.WaitForPageToLoad("30000");
Assert.AreEqual("Google",selenium.GetTitle());
selenium.Click("xpath=//div[@id='als']//font[@id='addlang']/a[2]");  //  Using XPath

Run selenium tests in NUnit

Download latest version of NUnit from http://www.nunit.org/index.php?p=download

After NUnit installation Go to -->Start--->Programs-->NUnit-->Click on NUnit

NUnit GUI will open.

Go to File--> Open Project--> Browse for .dll for the above project-->click on open

On Left Side bar we will the Name Space , Class name of the project and Methods present in the project.
Click on Run button 

                         
We will get the Result like below screenshot. If all the steps executed succesfully then we will get Green color bar other wise Red color with the error messages. 


If we want to see any output messages Goto-->Text Output tab at the bottom.

Example to verify Search Results

using System;
using System.Text;
using NUnit.Framework;
using Selenium;

namespace GoogleExample
{
    [TestFixture]
    public class homepage
    {
       ISelenium selenium;
       [SetUp]
        //Steps to be executed before execution of all steps
       public void setUpTest()
       {
           selenium = new DefaultSelenium("localhost",4444,"iexplore","http://google.co.in");
               //Here 4444 means port no of selenium server, iexplore for IE 
           selenium.Start();                                   // To start Selenium server  
           selenium.SetSpeed("2000");                 //To Control the execution speed
          selenium.WindowMaximize();                //To Maximize Browser window
          
       }

        [TearDown]
        //Steps to be executed after execution of all steps
        public void tearDownTest()
        {
         selenium.Stop();

        }

        [Test]
        // Steps to be written to verify the Result Status
        public void ResultsStatus()
        {
            selenium.Open("/"); // open url
            selenium.Type("name=q", "Testing"); // Type text in Text Field
            selenium.Click("name=btnK");    //click on button with name


            //Verifying results status

       
            if ((selenium.IsElementPresent("id=resultStats"))) 
             {
                 string a = selenium.GetText("id=resultStats"); //Get the text Results output
                 Console.WriteLine(a);     //To display output in the console of NUnit GUI
             }
             else
            {
                Console.WriteLine("Results not found");    //To display output in the console of NUnit GUI
            }
         }
      }
}

We need to install NUnit to run the above example.

Monday 24 October 2011

Configuring Selenium RC with .Net Client Driver


.NET client Driver can be used with Microsoft Visual Studio. To configure it with Visual do as Following.
·         Launch Visual Studio and navigate to File > New > Project.

·         Select Visual C# > Class Library > Name your project > Click on OK button.

·         A Class (.cs) is created. Rename it as appropriate.

·         Under right hand pane of Solution Explorer right click on References > Add References.

·         Select following dll files - nmock.dll, nunit.core.dll, nunit.framework.dll,ThoughtWorks. Selenium.Core.dll, ThoughtWorks.Selenium.IntegrationTests.dll, ThoughtWorks.Selenium.UnitTests.dll and click on Ok button


Now Visual Studio is ready for writing Selenium Test Cases.

Wednesday 19 October 2011

Running Selenium RC server from Microsoft Visual studio

1)      Tools ---->External Tools
2)      External Tools Window opened
Fill the following values
Title: Selenium Server (Name appear in Tools Menu)
Command: C:\Program Files\Java\jdk1.5.0_22\bin\java.exe (java installed directory)
Arguments: -jar selenium-server.jar (To execute a jar file)
Initial directory: D:\My Files\Selenium\selenium-remote-control-1.0.3\selenium-server-1.0.3
(Path of the selenium-server.jar file)
Now Selenium Server appears in Tools menu. We can directly run the selenium server by click on it. We can watch the status of the selenium server details in output window.

Tuesday 18 October 2011

View Cookie in Internet Explorer 7 & 8

To view cookie information in Internet Explorer 7 and 8 versions.

Follow the below steps

1) Open the site(i.e Cookie information for which site you are searching)
2) Click F12
3) Click Cache Tab
4) Select View Cookie Information

Then you get the cookie information about the particular site or domain name like below format.

Cookie Information - http://book.theautomatedtester.co.uk/chapter8


NAME visitorCount
VALUE 2
DOMAIN book.theautomatedtester.co.uk
PATH /
EXPIRES 11/9/2011 6:31:48 PM