我正在使用 specflow 来自动化我的测试。正如预期的那样,当任何 [Given-when-then] 方法说找不到元素时,它们会抛出异常。我想在每个场景之后调用的 [afterscenario] 方法中获取此异常的错误消息。 这可能吗?
例如下面是我需要捕获的错误信息
最佳答案
您正在寻找 ScenarioContext.Current.TestError
。我尝试查看 SpecFlow 文档,但我认为我只是通过在 Visual Studio 中使用 Intellisense 深入了解 ScenarioContext.Current
属性找到了这个属性。
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
}
}
}
}
}
为了避免在访问 ScenarioContext.Current
时在多线程上下文中运行测试时出现异常,您可以利用内置依赖注入(inject)框架将当前上下文作为构造函数参数传递给您的CommonHooks
类:
[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
}
}
}
}
关于c# - 如何获取由 specflow 场景的 [Given-when-then] 方法之一抛出的异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28049887/