Better handling ‘NoSuchElementException’ using simple remote web driver wrapper

While implementing test scenarios, I often write some element selectors wrong and finally get ‘NoSuchElementException’ when run the test. Unfortunately it does not specify, which selector caused the problem. Its message only says the following:

OpenQA.Selenium.NoSuchElementException: no such element
(Session info: chrome=45.0.2454.99)
(Driver info: chromedriver=2.10.267521,platform=Windows NT 6.3 x86_64)

So I need to waste time to locate exact failed selector using debugging…
Wouldn’t be nicer to have not found selector specified right in exception message? So it would be possible to troubleshoot the problems easily.
Ok, let’s  add it!

First prepare the environment. I use Visual studio 2013, update 5.
1. Create test project. Ensure that you have NUnit runner extension installed in VS.
2. Install following packages:

  <package id="CuttingEdge.Conditions" version="" targetFramework="net45" />
  <package id="NUnit" version="2.6.4" targetFramework="net45" />
  <package id="Selenium.WebDriver" version="2.47.0" targetFramework="net45" />
  <package id="WebDriverChromeDriver" version="2.10" targetFramework="net45" />

3. Modify UnitTest1 class to use NUnit.

    public class UnitTest1
        public void TestMethod1()
            using (var myDriver = new ExceptioHandleDriver(new ChromeDriver(new ChromeOptions())))
               var element = myDriver

                Assert.IsTrue(element != null);

4. Add driver implementation. Driver is wrapper around RemoteWebDriver and implements only few functionality, just to fit the demonstration purpose:

 public class ExceptioHandleDriver : IDisposable
        private readonly RemoteWebDriver _innerDriver;

        public ExceptioHandleDriver(RemoteWebDriver innerDriver)
            _innerDriver = innerDriver;

        public ExceptioHandleDriver GoTo(string url)
            return this;

        public IWebElement FindElement(By by)
                return _innerDriver.FindElement(@by);
            catch (NoSuchElementException e)
                throw new NoSuchElementException(string.Format("Element '{0}' was found.", @by), e);

        #region Dispose pattern implementation


        public void Dispose()

        public void Dispose(bool disposing)
            if (disposing)
                if (_innerDriver != null)


Now when we run the test (it assumes to be failed, do not worry), we could happily see better error representation:

Result Message:
OpenQA.Selenium.NoSuchElementException : Element ‘By.Id: unique-id’ was found.
—-> OpenQA.Selenium.NoSuchElementException : no such element
(Session info: chrome=45.0.2454.99)
(Driver info: chromedriver=2.10.267521,platform=Windows NT 6.3 x86_64)
Result StackTrace:

Posted in Selenium | Tagged | Leave a comment

MVC configuration – ‘path’ attribute inside ‘location’ section

This is post about specifying path attribute of location section in Web.config file. If you are not familiar with this section, go here

Examples in above article concern about ASP.NET where specifying path like ‘Page1.aspx’ is enough.
When I started mapping this knowledge to ASP.NET MVC, first time I failed.
As a test environment I used default ASP.NET MVC project (not empty) to have ready to work profject structure. What I wanted is to override key “test1” for my Index view. Index view was rendered through the Index action of Home controller. I started with following:

  <location allowOverride="false" path="Index">
      <add key="test1" value="test4" />

Unfortunately it did not work.

I found out that in MVCC, where routing module does all work, we need to specify full path to the action, not just the ‘action’ name. Like following (working code):

  <location allowOverride="false" path="Home/Index">

Note here: specifying the path started from ~/ (root in MVC) is not allowed here and will not be resolved to the proper path!

Posted in ASP.NET | Leave a comment

Add Visual Studio intellisense support for custom configuration section

On my main project we use heavily the awesome log4net framework. It could be quite easily configured but for some advanced configuration I need to constantly check the documentation. I personally prefer to have all required knowledge on how write configuration in Visual Studio.
Fortunately VS allows to add intellisense support for custom configuration section (like log4net or whatever you want).

As configuration file is still XML, what you need is to provide the XSD schema to the editor. And you got intellisense do hard work for you. See how:

  1. Find configuration file.
  2. Open file for edit. Its properties window should be seen in the bottom right corner of the VS editor (default settings). 
  3. Click on ‘Schemas’ row:
    Edit XSD schemas for XML
  4. You could see tons of already included XSD schemas that makes editing configuration file so playful! Click on “Add” to choose schema. I downloaded log4net XSD here beforehand.
    Manage XML Schemas
    Then you will see new schema now included into the configuration file schemas.
    Log4net XSD successfully added
  5. The last this is to test it. Start typing app.
    Intellisense power

Looks like it work now. Great!

So this was a tip on how to include custom configuration section intellisense support.

Image | Posted on by | 2 Comments

Reading large XML files. Performance comparison of different methods

For really large XML documents larger than 100 MB the idea to load entire document in memory could be not the best choice. Now let’s consider the other ways for reading those large files.

For our test lab we will create console project. Now let’s add simple domain class:

public class CustomDiscount
        public string Name { get; set; }
        public int Type { get; set; }
        public decimal Offer { get; set; }

In order to get test results let’s first create target Xml file and fill it with some discounts using following method:

private static void FillLargeXml(string filePath, int elementsCount)
    var random = new Random();
    var discounts = new CustomDiscount[elementsCount];
    for (int i = 0; i &lt; discounts.Length; i++)
        discounts[i] = new CustomDiscount()
                Offer = (decimal) (random.NextDouble()*200),
                Type = random.Next(1, 2),
                Name = Guid.NewGuid().ToString(&quot;N&quot;)

    var root = new XElement(&quot;root&quot;);
    Array.ForEach(discounts, d =&gt; root.Add(new XElement(&quot;CustomDiscount&quot;,
        new XElement(&quot;Name&quot;, d.Name),
        new XElement(&quot;Type&quot;, d.Type),
        new XElement(&quot;Offer&quot;, d.Offer))));

Parsing large xml using XmlSerialiser:

private static CustomDiscount[] DeserialiseLargeXml(string filePath)
    var xs = new XmlSerializer(typeof(CustomDiscountRoot));
    var res = (CustomDiscountRoot)xs.Deserialize(XmlReader.Create(filePath));
    return res.Discounts;

CustomDiscountRoot class:

public class CustomDiscountRoot
    public CustomDiscount[] Discounts { get; set; }

Parsing with LinqToXml

private static CustomDiscount[] ParseLargeXmlWitmXLinq(string filePath)
    var xElements = XElement.Load(filePath).Elements(&quot;CustomDiscount&quot;).ToArray();
    return xElements.Select(ConvertFrom).ToArray();

private static CustomDiscount ConvertFrom(XElement e)
    var value = e.Element(&quot;Name&quot;).Value;
    var s = e.Element(&quot;Type&quot;).Value;
    var value1 = e.Element(&quot;Offer&quot;).Value;

    return new CustomDiscount()
        Name = value,
        Type = int.Parse(s),
        Offer = decimal.Parse(value1, CultureInfo.InvariantCulture)

Parse using XmlReader:

private static CustomDiscount[] ParseLargeXmlWithXmlReader(string filePath)
    var discounts = new List&lt;CustomDiscount&gt;();
    using (var reader = XmlReader.Create(filePath))
        while (reader.ReadToFollowing(&quot;CustomDiscount&quot;))
            string name = reader.ReadElementContentAsString();

            int type = reader.ReadElementContentAsInt();

            decimal offer = reader.ReadElementContentAsDecimal();
            discounts.Add(new CustomDiscount
                    Name = name,
                    Type = type,
                    Offer = offer
    return discounts.ToArray();

Now let’s see the performance time (in milliseconds) comparison for different approaches of dealing with large XML docs.

Objects in XML 100.000 200.000 400.000 800.000 1.600.000
XmlReader 738 809 2294 3677 8379
LinqToXml 1092 1800 2581 5245 14888
XmlSerialiser 574 432 733 2962 3605

*Time counters were specified in milliseconds
*Each computation was repeated for 5 times
*.NET framework v4.0

It is easy to see that the fastest approach to parse large XML documents is using XmlSerialiser class which is also the most elegant and concise. It uses instance of XmlReader as input parameter so does not load entire document into memory.
The second for performance is XmlReader. Theoretically it should have the same performance as XmlSerialiser.Deserialise() method with more control over the process of reading the document. ( I really like its syntax now, it is much cleaner and handy in comparison for instance with OpenXmlReader that is used for reading Excel documents without its loading in memory)
The “looser” is using LinqToXml. It loads the entire xml into memory so that it document is really huge that OutOfMemory exception is possible there. But on not really large amount of data (something below 1.000.000 entire objects packed inside xml) this is neglectible.


For extremely large documents use either XmlSerialiser.Deserialise() method if you need the entire objects from xml, or use XmlReader if you need only part of the data.  It will prevent you from OutOfMemory exception and performance bottlenecks.

Posted in XML | Tagged | Leave a comment

Handling test data clean up in SpecFlow


This post describes how to handle scenario level clean-up in a predictable way.

Note: This blog post was originally written for SpecFlow 1.9 version.
In SpecFlow 2+ version you should use scenario scoped bindings  with  [BeforeScenario] execution order can be now controlled with an Order parameter.

Writing advanced UI tests with SpecFlow and Selenium often requires some test data to be created. During the tests execution this test data is changed. One of requirements for a good test is repeatedness. Test have to be executed multiple  times and should complete with the same results.

So we need some sort of clean-up procedures for our tests in order to satisfy above requirement. Let’s consider what SpecFlow could offer us in this case.


Hook is the statement of code that is executed after or before particular event. Here are the most useful from my mind:

  1. [AfterScenario(“MyTag”)] – code is executed after all the scenarios marked with @MyTag.
  2. [BeforeScenario(“MyTag”)] – code is executed before all the scenarios marked with @MyTag

You could find more info about SpecFlow hooks on the project wiki here.

Let’s consider very simple scenario, where we need some sort of clean-up procedures:

Scenario: Price is updated
Given: Price for product foo is 10$
When: Price is changed to 15$
Then: Product foo has price 15$ on the site

What we could expect when test is finished? That the price for product ‘foo’ is 15$.
But what happened when we try to repeat this test? Sure it will fail as now price is 15$. What we need is to organise cleanup action after test execution, so user will be bound to the ABC again.

How could we achieve such behaviour? Well using the hooks in such way.

public void AfterScenario()
    var title = ScenarioContext.Current.ScenarioInfo.Title;
    if (title == "Price is updated")
        //do some actions to restore previous state
    if (title == "SomeOtherTest")
        //do some clean-up for that

Usually logic inside if statement might be quite complex, as it requires some action to do and reuse the our Page Objects. So AfterScenario method become bloated and hard to read.

Let’s replace above statement with 2 separate methods and mark with our custom attribute:

[ScenarioCleanup("Price is updated")]
public void ResetPrice()
    //do some actions to reset the price

public void CleanupAfterOtherTest()
    //do some other actions

Code for newly created attribute;

public class ScenarioCleanup : Attribute
    public string ScenarioTitle { get; set; }

    public ScenarioCleanup(string scenarioTitle)
        ScenarioTitle = scenarioTitle;

And finally the code where all parts are gathered;

public class TestBehaviour
    public void BeforeTestRun()
        _teardownActions = BuildDictionary(this.GetType());

    public void AfterScenario()
        _commonTestBehaviour.ResolveScenarioCleanup(ScenarioContext.Current.ScenarioInfo.Title, this);
        //some other code, like disposing selenium driver or so

    [ScenarioCleanup("User changes company")]
    public void ResetBindedUser()
        //do some actions to rebound user to the initial company

    public void ResolveScenarioCleanup(string title, object instance)
        MethodInfo cleanupMethod;
        if (_teardownActions.TryGetValue(title, out cleanupMethod))
            cleanupMethod.Invoke(instance, null);

    private Dictionary<string, MethodInfo> _teardownActions;

    private Dictionary<string, MethodInfo> BuildDictionary(Type type)
        var withAttrs = type.GetMethods()
            .Where(m => m.GetCustomAttributes(typeof(ScenarioCleanup), false).Length > 0)
            .ToDictionary(key => ((ScenarioCleanup[])key.GetCustomAttributes(typeof(ScenarioCleanup), false))[0].ScenarioTitle, val => val);
        return withAttrs;

In short:

  1. Before TestRun via reflection all the cleanup methods init.
  2. When scenario is executed, AfterScenario() method runs
  3. In AfterScenario method, corresponding clean-up method is resolved and executed
Posted in Selenium, SpecFlow | Tagged , , | Leave a comment