c# - 如何获取由 specflow 场景的 [Given-when-then] 方法之一抛出的异常消息

标签 c# exception bdd specflow

我正在使用 specflow 来自动化我的测试。正如预期的那样,当任何 [Given-when-then] 方法说找不到元素时,它们会抛出异常。我想在每个场景之后调用的 [afterscenario] 方法中获取此异常的错误消息。 这可能吗?

例如下面是我需要捕获的错误信息

enter image description here

最佳答案

您正在寻找 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/

相关文章:

c# - 如何在 RESTful WCF API 中实现 HMAC 身份验证

c# - Form.Show() 没有显示它的子控件

c# - Crystal 报表列名不明确错误。

javascript - 检测服务器/站点对跨域 XMLHttpRequests 的支持?

r - 在 dplyr 的 mutate 中 try catch ?

java - 抛出异常并从 finally 返回 - Tomcat 挂起

javascript - 集成测试与本地存储交互的 JavaScript 的正确方法是什么?

c# - String.Join 返回 × 而不是次数?

scala - Scala 的 "specs"BDD 框架如何工作?

grails - IntelliJ中使用Easyb或Spock在Grails项目中使用“Test a little, code a little”