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.