Automated Tester

.science

This content shows Simple View

Selenium

Browser Profiles with Selenium

I decided to write this article after someone asked about browser profiles with Selenium in the IRC channel.

With Selenium we can specify a particular browser profile when instantiating our driver so if you happen to have specific browser setup requirements such as Firefox with certain plugins installed we can tell the driver to use this.

Setup

To begin with we will want to setup up our profile to be used. In this example we will use Firefox and use the Firefox profile manager.

To access this run “firefox -p” from Run.

profiles1

Which will load up the profile manager, here we will create a new profile and call it ‘QAToolsProfile’ – for this example we will choose the save folder as ‘Browser Profile’ on the desktop.

profiles2

profiles3

Next, start up firefox and add in the tools required for your new profile, I am going to add a tool called REST Client.

profiles4

profiles5

Right then! We now have a customised browser profile to call in our code.

Calling the Profile

As you might expect this is relatively easy as we just need to pass in the location of the profile which we dumped on the desktop:

private static void SetupFirefoxDriver()
{
string profileDir;

profileDir = @"C:\Users\user.name\Desktop\BrowserProfile";

FirefoxProfile profile = new FirefoxProfile(profileDir);
Driver = new FirefoxDriver(profile);
}

If we now say to a test to navigate to “chrome://restclient/content/restclient.html” we can automate the browser plugin. In this instance we can perform some API checks with RESTClient’s user interface. If we did not specify the profile then Firefox would load up with no extra frills.

profiles6

You can find more information on Browser Profiles with Firefox here.



Automation with AutoIt

This is a tool primarily used for automating windows applications but can also be used in conjunction with Selenium to deal with any windows dialogue boxes that Selenium on its own cannot manipulate. It can also interact with Active X dialogues. Generally speaking it is bad practice to implement this tool in your framework as it will only work with windows but if for example you find yourself on a project where you have little or no option it can be very useful, I have personally used this for a legacy application that was windows only and relied heavily on ActiveX but I would not recommend it for anything else!

Selenium on it’s own can do a lot with it’s builder actions and abilities to handle (to an extent) alert boxes, so don’t bring this into your solution unless you really need it. This is good for legacy applications that are not very browser friendly.

First off, download AutoIt:

www.autoitscript.com

AutoItX

Rather than go through the more traditional route of authoring VB Script in Auto IT’s Scite Editor (Explained below) we can import AutoItX – DLL/COM control which features a C# assembly. You still need to install AutoIt and also add the assembly to your references in Visual Studio.

Once setup we can start authoring C# with the goodies contained in AutoItX, lets dig in with an example.

public static void HandlePrintDialogue()
        {
            au3.WinWait(AiWindows.PrintWindow, "", 10);
            au3.WinActivate(AiWindows.PrintWindow);
            au3.Send(AiKeystrokes.Enter);
        }

This code handles IE’s print dialogue window after the user has clicked a print button on the page or pressed CTRL + P. To begin with we are waiting for a window with the title “Print” to appear on screen within 10 seconds. Please bear in mind the window you are looking for may be names differently in different versions of windows.

au3.WinWait(AiWindows.PrintWindow, "", 10);

Once found we are activating that window to be be manipulated in some way.

au3.WinActivate(AiWindows.PrintWindow);

Then we send an enter key press because with careful observation we know Enter defaults to “Ok” and the print job will be started.

au3.Send(AiKeystrokes.Enter);

You can do a lot more with AutoItX including making assertions on the content of windows dialogues, handling downloads and more.

Please refer to the following for a full list of functions: https://www.autoitscript.com/autoit3/docs/functions.htm

Scite Editor

Open the Script editor and type your VB Script to deal with the dialogue/ issue in question. In this example we are only sending keystrokes to the active window if it is titled as “Login”.

If Winactive ("Login") = 0 Then
   WinActivate("Login")
EndIf

Send ("Username")
Send ("{TAB}")
Send ("Password")
Send ("{ENTER}")

We can save this and compile it, AutoIt will create an *.exe which we can execute from our step definition in the selenium code:

public void HandleLoginPrompt()
        {
            Runtime run = Runtime.getRuntime();
            Process pp = run.exec("C:\\PathToFile\\AILoginScript.exe");
        }

Run the test and see the results.



Data Driven Specflow Testing

What is it?
Specflow has a plugin called Specflow + Excel to allow you to hoard data in a spreadsheet and run tests using the data contained within.

Example

  • Download Specflow + Excel from Nuget into your solution.
  • Write a normal looking Scenario Outline such as below and notice that there are no items in the example table and also notice the @Tag above the examples table; this is referencing the file we want to use that houses all of our data:
Feature: GoogleTest
In order to have data driven tests in specflow
As a tester
I want to be able to plug all of my data into a spreadsheet

@mytag
Scenario Outline: GoogleTest
Given I have navigated to Google
And I have entered  into the search field
When I press enter
Then the result containing  are shown on screen

@source:GoogleTest.xlsx
Examples:
| SearchTerm | Result |
  • Write out your Step Definitions as usual, no special changes or requirements are needed
  • Create a new Excel Spreadsheet called ‘GoogleTest.xlsx’ and include this in your solution
  • Enter your corresponding parameter values
SearchTerm Result
fish Official Fish site
foo bar foobar2000
specflow SpecFlow – Cucumber for .NET

These will now appear as tests in your test runner!

Specflow Excel



Structuring Projects with BDD, Specflow and Selenium in C#

Typically when I create a Specflow BDD solution, BDD elements are separated into Feature Files, Hooks, Step Definitions and Pages. These elements are separate folders or subsets of folders within the solution.
Code begins with the feature files written in Gherkin, feature files contain Scenarios which themselves execute test cases. Sometimes a scenario is just one test case or can be many iterations of a particular action. An example is listed below:

Scenario Outline: Sitemap Links
 And I click the sitemap link 'LinkName'
 Then I am taken to the sitemap page for 'LinkName'
Examples:
 | LinkName              |
 | Contact Us            |
 | Terms and Conditions  |
 | Privacy Policy        |

Generally we perform a set of actions and then assert the outcome at the end, in the scenario above we are searching for links in the sitemap section of the footer, selecting a result from a list and then asserting that we are taken to that particular page.

It helps greatly if these features are written in collaboration. In an ideal world features should be authored in a “three amigos” style with the project Business Analyst and Product Owner.

Gherkin generates Step Definitions which can be used across a set of feature files. It makes sense to group common ones together in one big Step Definition file for actions such as navigating to the site or logging in/out of the application. More feature specific steps are kept in separate files.

It is our aim to keep the code in step definitions short and clean, we do this by wrapping up selenium code and putting these methods in to the Pages .cs files. For example:

Given I have navigated to Test Environment

Generates the following Step Definition:

[Given(@"I have navigated to (.*)"]
public void GivenIHaveNavigatedTo(string website)
{

}

From here in one of the common Pages .cs files we have created the following method:

public void NavigateTo(string url)
{
this.context.Driver.Navigate().GoToUrl(url);
}

We try to keep the Selenium code wrapped up in these statements to keep the Step definitions easy to write. With this method in place our step definition looks like this:

[Given(@"I have navigated to (.*)"]
public void GivenIHaveNavigatedTo(string website)
{
Page.NavigateTo(URLS.TestEnvironment1)
}

Organising Tests
Tests are organised with @Tags which make groups of or individual tests easy to find in MS Test. They also have other important uses in hooks and can be used to execute a set of tests on a CI build.

For example all Sanity tests are labelled with @_Sanity this makes the whole suite of sanity tests easy to find and execute. If this tag was passed to a CI build then rather handily just the sanity tests would run on an overnight build rather than a lengthier @_Regression suite.

What’s with the underscore? Well that just keeps your tags at the top of the MS Test list if you happen to be using that test framework, depending on your preference of viewing them.

Hooks

Hooks are used primarily for the test run set up and teardown. Before a run we want to instantiate a driver and spin a browser up before any scenarios are automated, otherwise it would go nowhere fast. Similarly at the end of a test run we want to kill the browser off.

You can be a bit more clever with hooks and execute bits of code before or after certain features, steps, scenarios or scenario blocks. In order to keep an easy to understand codebase these must be used sparingly. This is because debugging can be harder and feature files can have all sorts of things happening that aren’t specified in English and that’s not what BDD is intended for.

For more information on hooks please visit: https://github.com/techtalk/SpecFlow/wiki/Hooks

Pages

This section of classes is where we keep all of the wrapped up Selenium code, which is a bit nasty. We wrap them up into helper methods to make our step definitions easier to write as described previously. This code should be kept clean and refactored and should encapsulate common practices and apply sensible programming practices such as DRY (Don’t Repeat Yourself).

The Selectors Page is where we keep a large number of constants, this is so that if an Id changes on the System Under Test you will only ever need to change it once to fix your broken test(s).

Rules

We also keep in mind a set of rules  when structuring the code which are:

  • No Selenium Code in Step Definitions
  • No Project Specific Methods in PageBase, use MainPage for these
  • All By.Criteria to be defined and referenced in selectors page
  • URLs and base URLs that aren’t in Gherkin must be constants
  • Create triptych Given/When/Then step definitions where necessary
  • Always copy generated methods to clipboard
  • No Thread.Sleeps in any step definitions, wait for something instead
  • Regions, regions, regions – use regions in code to keep it nice and tidy
  • “That” is a banned word in Gherkin
  • Replace all auto generated variable names with something sensible
  • All assertions have the optional message parameter populated except for AreEqual
  • Split Step Definitions out into sensible groupings/ filenames

Diagram

BDD Solution Architecture
BDD Solution Architecture

Base Solution

You can find a base solution here.

Wrap Up

There is a lot more you can do to improve this solution like putting in a clever environment selector, addition of Sauce Labs or BrowserStack and also Applitools Eyes. The way this is build is designed to give you scalability and organisation to cope as your test suite grows but you have to be strict with yourself and keep in mind the BDD Rules set out or things can get messy very quickly.



Welcome to Automated Tester.science

What’s all this then?

Automated Tester is a site for community and professionals to talk about and help each other in all things automated in the testing world. I will try to post snippets of what I know but the main intention is to drive use of the forums, comments and such like.

Who are you?

My name is Justin Holsgrove, I am a test automation engineer/ dev in test using C# .Net to develop testing solutions with Selenium Webdriver. Primarily in a BDD sense.

What’s with the .science suffix?

Well the reason is two-fold, firstly you could maybe  argue that testing is a science in itself, certainly in computing terms. Secondly, a domain name provider was giving the .science TLD away for free.

Please feel free to contribute to this site in any way you see fit that will benefit others in what they do. That may include guest posts, forumming, book plugging, whatever you like, it is your contributions that matter!




top