How to use Selenium + IDE with Visual Studio and C#

How to use Selenium + IDE with Visual Studio and C#

Contents

Contents

Installation. 0

Optional step – Selenium IDE for Firefox. 5

Converting Selenium IDE recorded Scripts to C# WebDriver code for Visual Studio. 6

Running tests. 8

Tips and Tricks with Selenium and C#. 9

Sample C# code generated with Selenium IDE. 9

Needed namespaces for tests. 11

Using a browser to performs test operations. 11

Using a test. 11

Imitating focus or hover over an element. 12

Waiting for the page to load or some operation. 12

Working with dynamic content/elements. 12

 

 

In this post I will cover the details about how to install Selenium + needed components to be able to test your web application.

Installation

The simplest way to use Selenium is to install the Selenium WebDriver nugget package to your Visual Studio project.

Open your Visual Studio create a project(of any kind). Then go to the References and select the “Manage Nugget Packages…”

Next search for the packages Selenium.WebDriver and Selenium.Support and install them.

You also need to install the “NUnit Framework”, so repeat the previous steps to install the NUnit framework package.

When you are ready your project references should look like this:

Next we need to install support for running test cases from the Visual Studio Test Explorer. Go to the top menu bar, from there select Tools and “Extension and Updates…”.

From the new window search online for NUnit Test adapter. Notice: Make sure that you have the right version. If you are using the latest Selenium version, then “NUnit 3 Test Adapter” is what you need.

Next step is to download Selenium driver support for different browsers. If you do not do this then you will not be able to run C# tests using Selenium.

First thing is to go and download the browser drivers which you want to use:

http://www.seleniumhq.org/download/

Scroll down to the Third Party drivers and download what you need. Then create a folder somewhere on your computer where you will put the browser drivers.

After this copy the full path to the folder and store it.

Go to the “Control Panel” > System > “Advanced Settings”

In the “System Properties” window, in the Advanced tab select the “Environmental Variables…”.

Next double click on the Path and press the New button. Then just paste in the path you stored to the browser drivers. This is used so that Visual Studio will know where to locate the needed browser drivers. If this is not done you will receive errors when trying to use the selenium tests.

After this restart your Visual Studio.

Optional step – Selenium IDE for Firefox

If you want to speed up making test case’s you can use Selenium IDE for firefox.

http://docs.seleniumhq.org/projects/ide/

To install this simply open you Firefox browser, go to the Extensions and search for the Selenium IDE.

To open the IDE in Firefox go to Tools > “Selenium IDE”. If the menu bar is not visible try pressing the ALT button.

Converting Selenium IDE recorded Scripts to C# WebDriver code for Visual Studio

First make sure that the recorded steps are converted into C# code. Go to Options > Format > C# / NUnit / WebDriver.

NOTICE: If the Format category under Options does not display any options:

Then do the following: Go to Options > Options and check “Enable experimental features”

Now to get you C# source code you need to tap the “Source” tab in the Selenium IDE main window.

Now you can create a new class in your Visual Studio project and copy & paste that code there and you are ready to run tests.

Running tests

To run tests all you need to do is open the “Test Explorer” in Visual Studio: In the menu bar Test > Window > “Test Explorer”

Now if you have a test and you have compiled your project then you should see your NUnit test with Selenium testing.

To run a test simply click the test with the second mouse button and run it from the options.

Tips and Tricks with Selenium and C#

Sample C# code generated with Selenium IDE

using System;

using System.Text;

using System.Text.RegularExpressions;

using System.Threading;

using NUnit.Framework;

using OpenQA.Selenium;

using OpenQA.Selenium.Firefox;

using OpenQA.Selenium.Support.UI;

namespace SeleniumTests

{

[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">TestFixture</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public class Untitled

{

private IWebDriver driver;

private StringBuilder verificationErrors;

private string baseURL;

private bool acceptNextAlert = true;

[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">SetUp</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void SetupTest()

{

driver = new FirefoxDriver();

baseURL = &quot;<a href="http://localhost:4000/&quot;">http://localhost:4000/&quot;</a&gt;;

verificationErrors = new StringBuilder();

}

[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">TearDown</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void TeardownTest()

{

try

{

driver.Quit();

}

catch (Exception)

{

// Ignore errors if unable to close the browser

}

Assert.AreEqual(&quot;&quot;, verificationErrors.ToString());

}

[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">Test</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void TheUntitledTest()

{

driver.Navigate().GoToUrl(baseURL + &quot;about:home&quot;);

driver.FindElement(By.Id(&quot;searchText&quot;)).Clear();

driver.FindElement(By.Id(&quot;searchText&quot;)).SendKeys(&quot;test&quot;);

}

private bool IsElementPresent(By by)

{

try

{

driver.FindElement(by);

return true;

}

catch (NoSuchElementException)

{

return false;

}

}

private bool IsAlertPresent()

{

try

{

driver.SwitchTo().Alert();

return true;

}

catch (NoAlertPresentException)

{

return false;

}

}

private string CloseAlertAndGetItsText()

{

try

{

IAlert alert = driver.SwitchTo().Alert();

string alertText = alert.Text;

if (acceptNextAlert)

{

alert.Accept();

}

else

{

alert.Dismiss();

}

return alertText;

}

finally

{

acceptNextAlert = true;

}

}

}

}

Needed namespaces for tests

Basically what you need is the NUnit framework, Selenium itself, different browsers support, support for UI and UI interactions.

using NUnit.Framework;

using OpenQA.Selenium;

using OpenQA.Selenium.Firefox;

using OpenQA.Selenium.Chrome;

using OpenQA.Selenium.Support.UI;

using OpenQA.Selenium.Interactions;

using OpenQA.Selenium.Interactions.Internal;

Using a browser to performs test operations

What this means is that you have to choose a browser driver of which you will create an object instance. With selenium you can code against an interface to make things easier.

So first you define the driver interface then later in the setup phase you instantiate it.

private IWebDriver driver;

[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">SetUp</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void SetupTest()

{

driver = new ChromeDriver();

baseURL = &quot;<a href="http://localhost:4000/&quot;">http://localhost:4000/&quot;</a&gt;;

verificationErrors = new StringBuilder();

}

Using a test

If you look at a sample code generated with the IDE you can see that a test function is defined with the Test attribute. Within this test function you can make things happen.

In the example below the test simply involved entering a search test in the Firefox main search engine.

[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">Test</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void TheUntitledTest()

{

driver.Navigate().GoToUrl(baseURL + &quot;about:home&quot;);

driver.FindElement(By.Id(&quot;searchText&quot;)).Clear();

driver.FindElement(By.Id(&quot;searchText&quot;)).SendKeys(&quot;test&quot;);

}

Imitating focus or hover over an element

There might be situation where you have some HTML element hidden and you want it to be displayed when the user goes over a certain location. Selenium will not now where the element is in this case and will throw an exception that the element was not found.

To fix this you need to simulate this hover over effect with the Actions class.

The example below will search for a div with a certain CSS class then using the Actions class and the MoveToElement function we simulate this step.

[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">Test</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void WorkEntryTest()

{

driver.Navigate().GoToUrl(baseURL + &quot;/&quot;);

System.Threading.Thread.Sleep(3000);

var element = driver.FindElement(By.CssSelector(&quot;div.myClass &quot;));

Actions action = new Actions(driver);

action.MoveToElement(element).Perform();

element.Click();

}

Waiting for the page to load or some operation

Now there are different ways to do this but the simples way is to sleep the thread where your test is running.

System.Threading.Thread.Sleep(3000);

Working with dynamic content/elements

This is a tricky one. I tried several approaches but wasn’t able to make them work. One of those approaches was to use XPath to find the elements in different ways:

· Absolute XPath

· Identify Element by starting Text

· Identify Element by containing Text

· Identify Element by Index

· Identify Element with reference of a closest stable element

· Identify Element by stable preceding Text

What worked for me was to use the WebDriverWait class. You are going to use the Until function with a condition to find that dynamic element:

http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp

The code below waits for a couple of seconds before searching for elements with a certain name attribute. Notice that in the example below I know that the needed element is the second one in the array returned by the Until function.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));

var selectElementWait = wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath(&quot;//select[@name=’minutes]&quot;)));

new SelectElement(selectElementWait[1]).SelectByText(&quot;30&quot;);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s