Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Exception message thrown by one of the specflow scenario's [Given-when-then] methods

I am using specflow for automating my test. As expected, when any of the [Given-when-then] methods say do not find and element, they throw exception. I want to get the error message of this exception in [afterscenario] method called after each scenario. Is this possible?

for example below is the error message I need to catch

enter image description here

like image 649
Ankit Avatar asked Dec 29 '25 21:12

Ankit


1 Answers

You are looking for ScenarioContext.Current.TestError. I tried looking through the SpecFlow documentation, but I think I found this property by just drilling down into the ScenarioContext.Current property using Intellisense in Visual Studio.

using TechTalk.SpecFlow;

namespace Your.Project
{
    [Binding]
    public class CommonHooks
    {
        [AfterScenario]
        public void AfterScenario()
        {
            Exception lastError = ScenarioContext.Current.TestError;

            if (lastError != null)
            {
                if (lastError is OpenQA.Selenium.NoSuchElementException)
                {
                    // Test failure cause by not finding an element on the page
                }
            }
        }
    }
}

To avoid exceptions when running tests in a multi-threaded context when accessing ScenarioContext.Current, you can utilize the build-in dependency injection framework to pass the current context in as a constructor argument to your CommonHooks class:

[Binding]
public class CommonHooks
{
    public CommonHooks(ScenarioContext currentScenario)
    {
        this.currentScenario = currentScenario;
    }

    private ScenarioContext currentScenario;

    [AfterScenario]
    public void AfterScenario()
    {
        Exception lastError = currentScenario.TestError;

        if (lastError != null)
        {
            if (lastError is OpenQA.Selenium.NoSuchElementException)
            {
                // Test failure cause by not finding an element on the page
            }
        }
    }
}
like image 198
Greg Burghardt Avatar answered Jan 03 '26 01:01

Greg Burghardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!