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

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
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With