繁体   English   中英

C#- 向实际的 specflow 错误打印一条附加消息

[英]C#- Print an additional message to the the actual specflow error

我正在尝试使用如下所示的 AfterStep 挂钩向实际的 specflow 错误消息添加一条附加消息,但它不起作用,有人可以建议更好的方法。

[AfterStep]
public void AfterStep()
{
    if (this.scenarioContext.ScenarioExecutionStatus == ScenarioExecutionStatus.TestError)
    {
        var stepName = this.scenarioContext.StepContext.StepInfo.Text;
        var stepTable = this.scenarioContext.StepContext.StepInfo.Table;
        var errorLength = this.scenarioContext.TestError.Message.Length;
        this.scenarioContext.TestError.Message.Insert(errorLength, "\r\n Failed at Step: " + stepName + "\r\n" + stepTable + "\r\n");
    }
}

我试图抛出另一个自定义异常以从 AfterStep 挂钩内部打印我的附加消息,但这会更改原始堆栈跟踪。

这个答案并不完全是您要问的,但我希望它能体现您要实现的目标的精神。

在这种情况下,我的首选做法是使用SpecFlow Output API来添加更多关于失败的上下文。

长格式的说明在上面的链接中,但您可以将ISpecFlowOutputHelper注入到您的步骤定义类中。 这将允许您在给定步骤中在 SpecFlow output 中写入其他行。

通常,我会使用try/catch语句来捕获步骤执行期间发生的异常,然后我会使用ISpecFlowOutputHelperWriteLine方法来打印一些附加信息。

这允许您在发生的步骤中打印上下文,我发现这在审查失败的场景时很有用。

我实施了这个来修复它。 这会打印出我想要打印的消息,还会显示实际的堆栈跟踪。

[AfterStep]
        public void AfterStep()
        {
            if (this.scenarioContext.ScenarioExecutionStatus == ScenarioExecutionStatus.TestError)
            {
                var errorMessage = this.scenarioContext.TestError.Message;
                var stepName = this.scenarioContext.StepContext.StepInfo.Text;
                var stepTable = this.scenarioContext.StepContext.StepInfo.Table;
                var exception = this.scenarioContext.TestError.GetBaseException();
                exception.GetType().GetField("_message", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(exception, "Failed at Step: \r\n" + stepName + "\r\n" + stepTable + "\r\n Actual Error: \r\n" + errorMessage);
                var ex = ExceptionDispatchInfo.Capture(exception);
                ex.Throw();
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM