Automated Tester

.science

This content shows Simple View

C#

Setting up Marionette/ GeckoDriver

 

Firefox will crash if you are using the Webdriver implementation for FirefoxDriver with Firefox v47 and beyond. This needs to be replaced with Mozilla’s GeckoDriver/ Marionette. At the time of writing it is still in a pre-release stage; meaning you may get unpredictable results against the current stable version of Firefox. You may want to use it with Firefox Nightly or Firefox Developer.

Below are some steps to get you going with Marionette/ Geckodriver C# .Net:

  • Download the latest release here
  • Extract the *.exe middleware and rename it to ‘wires.exe’
  • Place ‘wires.exe’ in to the given source code location
  • Include ‘wires.exe’ into your Solution and set properties to ‘Copy if Newer’

To set the Driver up in code, I have found the following works well in C# .Net:

            FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();
            service.FirefoxBinaryPath = @"C:\Path\to\your\FF\exe.exe";
            FirefoxOptions options = new FirefoxOptions();
            options.AddAdditionalCapability(CapabilityType.AcceptSslCertificates, true);
            TimeSpan t = TimeSpan.FromSeconds(10);

            Driver = new FirefoxDriver(service, options, t);

Note that you need to put in the path to your Firefox *.exe or add it to your system Path variable.

If you are experiencing issues I would recommend having a look at the project bug list or the project GitHub issues page before raising any issues. There is also much more information over at the Mozilla page for Marionette.



Recording Videos of your Selenium Tests

It is good practice to take a screen grab of test failures and review them later, particularly if you have some bizarre wait or timeout error that can be difficult to pin down but sometimes even these can lead you down the wrong path or not give enough context to what went wrong. This led me to explore being able to capture videos of running tests that can be scrutinised at a later time, much like you get when you run tests in SauceLabs or BrowserStack.

I created a helper class called RecordVideo and pulled down a NuGet package called Microsoft Expression Encoder. You will also need to install Microsoft Expression Encoder 4.

Having set up a start (and stop) recording method we can easily capture tests in and write them out to file with the help of our set up or specflow hooks.

Here’s how:

using System;
using Microsoft.Expression.Encoder.ScreenCapture;

public class RecordVideo
{
private static readonly ScreenCaptureJob vidRec = new ScreenCaptureJob();

public static void StartRecordingVideo(string scenarioTitle)
{
string timestamp = DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss");
vidRec.OutputScreenCaptureFileName = @"C:\Test Videos" + scenarioTitle + " " + timestamp + ".wmv";
vidRec.Start();
}

public static void EndRecording()
{
vidRec.Stop();
vidRec.Dispose();
}
}

We can now call these in our setup/ teardown (in my case I’m using Scenario Hooks) and use the test case name for the file title along with a timestamp.

[BeforeScenario]
public void BeforeScenario()
{
RecordVideo.StartRecordingVideo(ScenarioContext.Current.ScenarioInfo.Title);
objectContainer.RegisterInstanceAs(new PageContext(TestRunContext.Driver));
}
[AfterScenario]
public void AfterScenario()
{
if (ScenarioContext.Current.TestError != null)
{
TakeScreenShot.SaveScreenShot(TestRunContext.Driver, TestFailurePath + ScenarioContext.Current.ScenarioInfo.Title + ".jpeg");
}

RecordVideo.EndRecording();
}

Be sure to put something in place to clear the directory out of videos on each run or you might find yourself running out of disk space quite quickly.



Mobile Emulation with ChromeDriver

We can use ChromeDriver to run automated Selenium tests against a whole stack of different devices with Chrome Dev Tools Mobile Emulation option.

Devices currently supported at the time of writing:

  • Amazon Kindle Fire HDX
  • Apple iPad
  • Apple iPad Mini
  • Apple iPhone 4, 5, 6 & 6+
  • Blackberry Playbook
  • Blackberry Z30
  • Google Nexus 4, 5, 6, 7 & 10
  • LG Optimus L70
  • Laptop with HiDPL Screen
  • Laptop with MDPI Screen
  • Laptop with touch
  • Nokia Lumia 520
  • Nokia N9
  • Samsung Galaxy Note 3
  • Samsung Galaxy Note II
  • Samsung Galaxy Note S III
  • Samsung Galaxy S4
Discovering the options available

ChromeDriver Mobile Emulation

Now it’s just a case of passing the device string to ChromeOptions’ EnableMobileEmulation option when instantiating the driver, like so:

public static void SetupIPadDriver()
{
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.EnableMobileEmulation("Apple iPad");
Driver = new ChromeDriver(chromeOptions);
}

Kick your test off and see it running in chrome but to the specification you supplied in the ChromeDriver option. There are of course subtle differences between emulators and real devices, weigh up the pros and cons for yourself and have a look at the official documentation.



API Testing with Specflow

I’m a big fan of Specflow/ Cucumber, it’s great for creating tests to run against a front end with webdriver but what if we want to keep that same plain English BDD approach and apply it against an API for automated API Testing? It’s certainly possible and this article will cover the basics to get you up and running.

I am going to assume you have a framework set up and in place, you can even use a webdriver based solution as described previously, although you may wish to run it with a headless driver.

I’m also going to add a SOAP endpoint to my solution and write a test in Gherkin, this endpoint is the publicly available Global Weather SOAP endpoint available here:

http://www.webservicex.com/globalweather.asmx?wsdl

This WSDL generates 2 service operations, GetCitiesByCountry (to get a list of all the cities for any country) and GetWeather (to get weather for any city/country combination).

Let’s add the WSDL somewhere we can use it in Visual Studio. If you right click your project and go to Add > New > Service Reference, you will be presented with a dialogue in which you can paste in the WSDL, click Go and give it an appropriate name.

Add Service Reference for API Testing

Click OK, you should see a new Service References folder in your solution. Lets begin formulating a test for our API Testing suite.

@API
Scenario Outline: Get Cities
Given I query the API
Then I can retrieve <City> from <Country>

Examples:
| City        | Country        |
| Reims       | France         |
| London      | United Kingdom |
| Agra        | India          |
| Porto Santo | Portugal       |
| Cancun      | Mexico         |
| Pretoria    | South Africa   |
| Melbourne   | Australia      |

We’re going to need a helper class which I will call ‘GeoHelper’ where we can reference the endpoint and then make some methods we can call from the step definition. Below I am passing a string value to the ‘GetCitiesByCountry’ extension on the endpoint and returning the result. Then I have created another helper method which takes that result and asserts the city is present in the response.

public class GeoHelper
{
     private readonly GlobalWeatherSoap globalWeather = new GlobalWeatherSoapClient();

     public string GetCitiesByCountry(string country)
     {
          var x = globalWeather.GetCitiesByCountry(country);
          return x;
     }

     public void CheckCityNameIsPresent(string countryName, string cityName)
     {
          Thread.Sleep(200);
          Assert.IsTrue(GetCitiesByCountry(countryName).Contains(cityName));
     }
}

So our step definition calls this like so:

private readonly GeoHelper geo = new GeoHelper();

[Then(@"I can retrieve (.*) from (.*)")]
public void ThenICanRetrieveFrom(string cityName, string countryName)
{
     geo.CheckCityNameIsPresent(countryName, cityName);
}

And that in brief is how we can leverage the use of Specflow for API Testing.



Interacting with Dropdown lists with Selenium in C#

This article briefly explains how to, or at lease how I interact with dropdown menus in C#. Generally speaking I try to pass through the identifier and the value to select to a helper method which carries out the task.

Lets have a look at a typical step definition, first we’re waiting for the element to appear on screen and then selecting the option by value.

[When(@"I select the organisation (.*)'")]
public void WhenISelectTheOrganisation(string orgName)
{
Page.WaitForElementByClass(ClassName.Organisation);
Page.SelectFromDropDownByClass(ClassName.Organisation, orgName);
}

So lets look at SelectFromDropDownByClass:

public void SelectFromDropDownByClass(string dropDownClass, string dropdownValue)
{
new SelectElement(Context.Driver.FindElement(By.ClassName(dropDownClass))).SelectByText(dropdownValue);
}

We’re creating a new instance of Webdrivers’ SelectElement and passing through the class name and text of the item in the dropdown, keeping the identifier variable ensures we can reuse the same method elsewhere in the solution, you can interact and select items in other ways from dropdowns and also use other identifiers as necessary such as Id, CssSeleector and XPath.




top