Search code examples
c#exceptionbddspecflow

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


Solution

  • 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
                }
            }
        }
    }