Powered By Blogger

Search Here!

Showing posts with label Selenium RC. Show all posts
Showing posts with label Selenium RC. Show all posts

Saturday, July 14, 2012

WebdriverBackedSelenium in C# using WebDriver !

Using WebDriverBackedSelenium with different browser(s) setting contains the .NET bindings for the older, more procedural Selenium Remote Control (or Selenium RC) API, but implemented using the newer WebDriver technology. It does not require a running instance of the Selenium Server.

if (Browser.Equals("IE"))
            {
                string ieDriverPath = ConfigurationManager.AppSettings["ieDriverPath"];
                var options = new InternetExplorerOptions { IntroduceInstabilityByIgnoringProtectedModeSettings = true };
                WebDriver = new InternetExplorerDriver(ieDriverPath, options);
                BackedSelenium = new WebDriverBackedSelenium(WebDriver, ConfigurationManager.AppSettings["browserUrl"]);
                BackedSelenium.Start();
WebDriver.Navigate().GoToUrl(ConfigurationManager.AppSettings["browserUrl"]);

            }
            if (Browser.Equals("Firefox"))
            {
                WebDriver = new FirefoxDriver();
                BackedSelenium = new WebDriverBackedSelenium(WebDriver, ConfigurationManager.AppSettings["browserUrl"]);
                BackedSelenium.Start();
WebDriver.Navigate().GoToUrl(ConfigurationManager.AppSettings["browserUrl"]);
            }
            if (Browser.Equals("Safari"))
            {
                WebDriver = new SafariDriver();
                BackedSelenium = new WebDriverBackedSelenium(WebDriver, ConfigurationManager.AppSettings["browserUrl"]);
                BackedSelenium.Start();
WebDriver.Navigate().GoToUrl(ConfigurationManager.AppSettings["browserUrl"]);
            }

Tuesday, June 5, 2012

Behaviour Driven Development (BDD) in .Net using SpecFlow, Selenium RC and MS Test !

BDD Using SpecFlow using .Net and MS TEST

I have been working on the Behaviour Driven Development (BDD) using SpecFlow for .Net and I felt it is fun. According to me, it is a Tester’s tool rather than a Developer’s tool and I felt it is worth sharing. Kindly refer the wiki for more theoretical info on BDD: http://en.wikipedia.org/wiki/Behavior_Driven_Development


System Requirements:
Windows 7 as OS
Microsoft Visual Studio 2010 as IDE
SpecFlow as BDD tool for .Net
Selenium as a Test Automation Tool

Referencing the SpecFlow:
1. Install the SpecFlow software on your machine.
2. In Visual Studio, Go to the Project -> Add Reference menu item.
3. When the Add Reference dialog appears, click on ‘Browse’ and navigate to C:\Program Files (x86)\TechTalk\SpecFlow and select TechTalk.SpecFlow.dll.
4. Finally, the solution Explorer should look like this:

Consider a sample user story:

Feature: User Creation
In order to Create user
As a Workspace admin
I want to create a w s user

Let me write a test scenario for the above story:

Scenario Create New User

When I enter username in the username field
And I enter password in the password field
And I press Login
Then the response Page is Course Enrolment
When I click the Create New User link
User popup
When I click the Save button
Then It s
And Enter the user details in Create Ne
would display successful message New user created successfully

Creating a new SpecFlow feature file:

1. Context-click on the project name ‘SpecflowTest’ in the Solution Explorer
2. Select Add -> New Item
3. Select the ‘SpecFlow Feature File’ and save it as ‘_Feature.CreateNewUser.feature’
4. Specflow creates a new file “ _Feature.CreateNewUser.feature ” and a designer file “ _Feature.CreateNewUser.feature.cs“. The default content of the Specflow file is in the Gherkin format.
5. The default content of the file is as shown is below:

Feature: Addition
In order to avoid silly mistakes
As a math idiot
I want to be told the sum of two numbers

@mytag
Scenario: Add two numbers

Given I have entered 50 into the calculator
And I have entered 70 into the calculator
When I press add
Then the result should be 120 on the screen

6. Change the contents of the file to the new scenario as below and the Specflow generates a feature file ‘ _Feature.CreateNewUser.feature.cs ’:

Add Scenario according to your Feature:

Feature: User Creation
In order to Create user
As a Workspace admin
I want to create a ws user

Background:
Given I open frmLogin.aspx?mode=admin in the browser

@sprint
@alternative_syntax
Scenario Outline: Create New User
When I enter in the username field
And I enter in the password field
And I press Login
Then the response Page is Course Enrollment
Examples:
|username |password|
|sel_ws_admin|password2|
When I click the Create New User link
And Enter the user details in Create New User popup
| Field | Value |
| txtPassword | password1 |
| txtFirstName | QA |
| txtLastName | BDD |
| txtEmail | bdd@gmail.com |
When I click the Save button
Then It should display successful message New user created successfully


1. Rename the class ‘Class1.cs’ to ‘ _Feature.CreateNewUser.cs’.
2. Context-click on the feature file ‘GoogleSearch.feature’ and select …… System generates a specification file ‘…..’ as shown below.


[Binding]
public class CreateNewUserDefinitions : SeleniumStepsBase
{
// Purpose: Creation Readonly Object(s)
readonly NewUserPage _newUserPage = new NewUserPage();

#region Locator
private const string Button_Signin = "//button[@class='lgn_btn']";
#endregion Locator

// Purpose: Step Implemented To Enter Username For Ws Admin
[When(@"I enter (.*) in the username field")]
[Given(@"I enter (.*) in the username field")]
public void EnterSomethingIntoThUsernameField(string username)
{
// Purpose: Calling Method To Enter Username in Username Field For Ws Admin
Selenium.Type("username", username);
ScenarioContext.Current["username"] = username;
}

// Purpose: Step Implemented To Enter password For Ws Admin
[When(@"I enter (.*) in the password field")]
[Given(@"I enter (.*) in the password field")]
public void EnterSomethingIntoThePasswordField(string password)
{
// Purpose: Selenium Method To Enter Password For Ws Admin in Password Field
Selenium.Type("password", password);
}


// Purpose: Step Implemented To Click on SignIn Button For Ws Admin
[When("I press Login")]
[Given("I press Login")]
public void WhenIPressLogin()
{
// Purpose: Selenium Method To Click on SignIn Button For Ws Admin
Selenium.Click(Button_Signin);
Selenium.WaitForPageToLoad(ConfigurationManager.AppSettings["Timeout"]);
}


// Purpose: Step Implemented To Click on 'Create New User' link in Ws
[When(@"I click the Create New User link")]
public void WhenIClickTheCreateNewUserLink()
{
// Purpose: Calling Method To Click on 'Create New user' Link in Ws
new AdminToolPage().StepClickCreateNewUserLinkWs();
}


// Purpose: Step Implemented To Fill User Details
[When(@"Enter the user details in Create New User popup")]
public void WhenEnterTheUserDetailsInCreateNewUsePopup(Table table)
{
// Purpose: Calling Method To Fill User Details
_newUserPage.StepFillUserNameInWs();
foreach (var tableRow in table.Rows)
{
Selenium.Type("//input[@id='" + tableRow["Field"] + "']", tableRow["Value"]);
}
}

// Purpose: Step Implemented To Click on Save Button for User Creation
[When(@"I click the Save button")]
public void WhenIClickTheSaveButton()
{
// Purpose: Calling Method To Click on Save Button for User Creation
_newUserPage.StepClickUserSaveButtonInWs();
}

// Purpose: Step Implemented To Verify Success Message on User Creation in Ws
[Then(@"It should display successful message New user created successfully")]
public void ThenItShouldDisplaySuccessfulMessage()
{
// Purpose: Caling Method To Verify Success Message on User Creation in Ws
new AdminToolPage().StepSuccessMessageOnUserCreatedWs();
}
}
}

Creating a Static class for defining the browser selection:


[Binding]
public static class SeleniumSupport
{
private static ISelenium _selenium;

// Purpose: Method Implemented To Get The Status of Test Scenario Web Seesion
private static bool ReuseWebSession
{
get { return ConfigurationManager.AppSettings["ReuseWebSession"] != "true"; }
}

// Purpose: Action Taken by Before Test Scenario Starts
[BeforeScenario("sprint")]
public static void BeforeWebScenario()
{
// Purpose: Starts Selenium Instance Before Test Scenario Starts
StartSelenium();
}

// Purpose: Action Taken by After Test Scenario Ends
[AfterScenario("sprint")]
public static void AfterWebScenario()
{
// Purpose: Stop Selenium Instance After Test Scenario Ends
if (ReuseWebSession)
StopSelenium();

Assert.AreEqual("", ScenarioContext.Current.SeleniumErrors().ToString(), "Selenium verification errors");
}


// Purpose: Method Implemented To Start Selenium Instance
public static void StartSelenium()
{
SeleniumProcess.Start();
if (_selenium == null)
{
if (Playback.IsInitialized)
{
Playback.Cleanup();
}
Playback.Initialize();
_selenium = new DefaultSelenium("localhost", 4444, ConfigurationManager.AppSettings["browser"], ConfigurationManager.AppSettings["browserUrl"]);
_selenium.Start();
try
{
_selenium.Open(ConfigurationManager.AppSettings["browserUrl"]);
_selenium.WindowMaximize();
}
catch (Exception e)
{
throw new Exception("Uanble To Start Selenium Server with Base Url: Please check your network settings.");
}
}

ScenarioContext.Current.SetSelenium(_selenium);
}


// Purpose: Method Implemented To Stop Selenium Instance
public static void StopSelenium()
{
if (_selenium == null)
return;

try
{
_selenium.DeleteAllVisibleCookies();
_selenium.Stop();
_selenium.Close();
}
catch (Exception ex)
{
Debug.WriteLine(ex, "Selenium stop error");
}
_selenium = null;
Console.WriteLine("-> Selenium stopped");
SeleniumProcess.Stop();
}
}

// Purpose: Method Implemented To Web Test Scenarios
public static class ScenarioContextWebExtensions
{
public static ISelenium Selenium(this ScenarioContext scenarioContext)
{
try
{
var result = (ISelenium)ScenarioContext.Current["selenium"];
return result;
}
catch (Exception)
{
throw new Exception("selenium is not started");
}
}

// Purpose: Method Implemented To Get The Selenium Instance in Current Test Scenario
public static bool IsSeleniumRunning(this ScenarioContext scenarioContext)
{
return ScenarioContext.Current["selenium"] != null;
}

// Purpose: Method Implemented To Set Selenium Property
public static void SetSelenium(this ScenarioContext scenarioContext, ISelenium selenium)
{
ScenarioContext.Current["selenium"] = selenium;
ScenarioContext.Current["selenium-errors"] = new StringBuilder();
ScenarioContext.Current["StepCounter"] = 0;
}

// Purpose: Method Implemented To Handle Selenium Unexpected Error(s)
public static StringBuilder SeleniumErrors(this ScenarioContext scenarioContext)
{
var result = (StringBuilder)ScenarioContext.Current["selenium-errors"];
Assert.IsNotNull(result, "selenium is not started");
return result;
}
}

Executing the Tests: MS Test

For using MS Test, we need to add configuration in app.config
<configSections>
<section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow"/>
configSections>

<specFlow>
<language feature="en-US" />
<unitTestProvider name="MsTest.2010" />
<runtime detectAmbiguousMatches="true"
stopAtFirstError="false"
missingOrPendingStepsOutcome="Inconclusive" />


<trace traceSuccessfulSteps="true"
traceTimings="false"
minTracedDuration="0:0:0.1" />
specFlow>

Friday, April 27, 2012

Selenium RC: Android Testing using C# !

We can use Selenium RC for Android Testing in C# code, here below how to use this :)


 public static ISelenium GetSeleniumInstance()
        {
            return Thread.GetData(Thread.GetNamedDataSlot("SeleniumInstance")) as ISelenium;
        }


public static IWebDriver GetWebDriverInstance()
        {
            return Thread.GetData(Thread.GetNamedDataSlot("WebDriverInstance")) as IWebDriver;
        }       
-------------------------------
        IWebDriver _webDriver;
        protected IWebDriver WebDriver { get { return GetWebDriverInstance(); } }
        ISelenium _selenium;
        protected ISelenium Selenium { get { return GetSeleniumInstance(); } } 
------------------------------
const BrowserUrl = ConfigurationManager.AppSettings["browserUrl"]; // Defined in app. config


            _webDriver = new AndroidDriver();
            _webDriver.Navigate().GoToUrl(browserUrl);
            _selenium = new WebDriverBackedSelenium(_webDriver, BrowserUrl);
            _selenium.Start();
            Thread.SetData(Thread.GetNamedDataSlot("WebDriverInstance"), _webDriver);
            Thread.SetData(Thread.GetNamedDataSlot("SeleniumInstance"), _selenium);

Note: I am using all Dll's of version 2.6.0.0 

Thursday, April 26, 2012

Selenium RC: Search Text using Pagination !

Sometimes, we want to search a value in absence of search function due to it's not implemented. There is a problem through Selenium to get the value in a table that contains pagination. This method helps you to find search value from the table using pagination.  tableName is the Table locator and searchText is the name of the text that you want to search.


        public static int SearchTextFromPaginationGrid(string tableName, string searchText)
        {
            ISelenium Selenium = GetSeleniumInstance();
            int table_employee;
            string gridID = string.Empty; ;
            bool value = true;
            do
            {
                string get_text = Selenium.GetText(gridIDLoc);
                 table_employee  = get_text.IndexOf(searchText);
                if (gridIDLoc.Contains("'"))
                {
                    string[] SplittedLoc = gridIDLoc.Split('\'');
                    gridID = SplittedLoc[1];
                }
                value = Selenium.IsElementPresent("id=" + gridID + "$next");
                if (value == true)
                {
                    Selenium.Click("id=" + gridID + "$next");
                    Thread.Sleep(2000);
                }
                WaitUntilElement(gridID);
            } while (value && table_txt < 0);
            return  table_employee;
        }

Tuesday, April 24, 2012

Selenium RC: Create Log Files

This C# method provides you to create verification results log in HTML format, you can change the format according to your need also it would take the screen shots of the FAILED log(s) and saves in a drive.


public static void Logs(string Logtext, string Status)
        {
            ISelenium Selenium = GetSeleniumInstance();
            string LogMessage;
            string StatusTest = Status.ToUpper();
            string time = Time_Stamp();
            String DriveName = ConfigurationManager.AppSettings["LogDriveName"]; //  in app.config file.
            String ErrorFileName = String.Concat(DriveName, ":\\Error_History.html");
            try
            {               
                String logsFileName = string.Empty;
                switch (StatusTest)
                {
                    case "PASSED":
                        logsFileName = String.Concat(DriveName, ":\\Passed_Results.html");
                        LogMessage = string.Format("{0},\"  \"{1},\"  \"{2}", Logtext, time, StatusTest);
                        break;
                    case "FAILED":
                        logsFileName = String.Concat(DriveName, ":\\Failed_Results.html");
                        string error = Generate_Unique_variable("Error") + ".png";
                        Selenium.CaptureScreenshot(DriveName + ":\\Selenium_Screenshots\\" + error);
                        LogMessage = string.Format("{0},\"  \"{1},\"  \"{2}", Logtext, time, StatusTest);
                        break;
                    default:
                        logsFileName = String.Concat(DriveName, ":\\Failed_Results.html");
                        LogMessage = string.Format("{0},\"  \"{1},\"  \"{2}", Logtext, time, StatusTest);
                        break;
                }
                WriteLogs(logsFileName, LogMessage);//write logs to appropriate log file.
                WriteLogs(ErrorFileName, LogMessage);// write all the logs to error history
            }
            catch (Exception ex)
            {
               WriteLogs(string.Concat(DriveName, ":\\Failed_Results.html"),String.Concat(ex.Message,"FAILED"));
            }              
        }


//  WriteLogs Method

private static void WriteLogs(string FileName, String LogMessage)
        {
            //Delete if the file is old
            if (File.GetLastAccessTime(FileName) < DateTime.Now.Subtract(new TimeSpan(24, 0, 0)))
            //if the file does not exist, GetLastAccessTime returns minimum datetime value
            {
                File.Delete(FileName);                
            };
            LogMessage = String.Concat(LogMessage, "\r\n");
            //Append The Message To The File
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(FileName, true))
            {
                file.WriteLine(LogMessage);
                file.Close();
            }
        }

You can call this generic method by using:
Logs("The Log generated.", "PASSED"); or
Logs("The Log not generated.", "FAILED");

Selenium RC: Find Row Number of Element

This C# method gives you the table row no.of the element. You need to pass the cloumn no. in which you want to make search, ReferenceText the text you want to find out and table locator, after then you could perform any action that row no.


public static int GetRowWithCellText(string columnnum, string ReferenceText, string TableLocator,int startFromRowNum=0)
        {
            ISelenium Selenium = GetSeleniumInstance();
            for (int i = startFromRowNum; ; i++)
            {
                try
                {
                    string elementPresent = Selenium.GetTable(TableLocator + "." + i.ToString() + "." + columnnum).Trim();
                    if (elementPresent.Contains(ReferenceText))
                    {
                        return i;
                    }
                }
                catch (Exception)
                {
                    break;
                }
            }
            return -1;
        }

Selenium RC: RedirectToPage


There are various scenarios when we need to switch in between different URL's. This C# method helps to redirecting page from one to another in a very generic manner.

public static void RedirectToPage(string url)
        {
            ISelenium Selenium = GetSeleniumInstance();
            Selenium.SelectWindow("");
            Selenium.GetEval("javascript{ (function() { var txt=selenium.browserbot.getCurrentWindow().location ='" + url + "'; return '';})(); }");
        }

Selenium RC: Select and Close Window


This C# method provides you to select the pop-Up window name and close it in a definite interval of time. You need to pass pop-Up window name and time to wait in milliseconds.


public static void SelectAndCloseWindow(string popUpName, int insertDelay)
        {
            ISelenium Selenium = GetSeleniumInstance();
            Selenium.SelectWindow(popUpName);
            Selenium.Close();
            if (insertDelay > 0)
            Thread.Sleep(insertDelay);
        }