使用 Specflow 和 xUnit 2 (ITestOutputHelper) 进行记录

问题描述 投票:0回答:4

不幸的是,我在本地通过了 Specflow 测试,但在 VSO Build vNext 服务器上失败了,我确实需要在测试运行期间查看详细信息,以便我可以弄清楚发生了什么。

但是我正在努力尝试将

ITestOutputHelper
注入像这样的Specflow绑定中

public SomeSteps(ITestOutputHelper outputHelper)

但 Specflow 抱怨该消息

BoDi.ObjectContainerException Interface cannot be resolved: Xunit.Abstractions.ITestOutputHelper (resolution path: ...)

到底如何在 Specflow 测试期间查看日志和查看输出?

c# specflow xunit xunit2
4个回答
3
投票

不确定我是否使用较新的版本,现在更容易了,但这似乎对我有用:

ScenarioContext.Current.ScenarioContainer.Resolve<ITestOutputHelper>().WriteLine("Hello");

2
投票

这是我能想到的最好的,它并不理想,但它确实实现了你想要的。

您创建一个新类来实现生成的 xunit 类。在我的示例中,生成的类称为

YourNormalFeatureClass

public class SpecialTest : YourNormalFeatureClass
{
    private Xunit.Abstractions.ITestOutputHelper helper;

    public SpecialTest(ITestOutputHelper helper) : base()
    {
        this.helper = helper;   
    }

    public override void ScenarioSetup(ScenarioInfo scenarioInfo)
    {
        base.ScenarioSetup(scenarioInfo);

        // you'd want a better way to keep track of this string
        TechTalk.SpecFlow.TestRunnerManager.GetTestRunner().ScenarioContext.Set(this.helper, "helper");
    }

}

现在,您可以通过

 从步骤文件中访问您的 XUnit 
ITestOutputHelper

var helper = this._scenarioContext.Get<Xunit.Abstractions.ITestOutputHelper>("helper");
helper.WriteLine("output from within the steps file that will be written to xunit!");

您需要对

helper
变量采取防御措施,以确保您不会得到任何
NullReferenceException

这样做的缺点是,您现在拥有同一测试的 2 个副本,因为您继承了旧测试。所以在这种情况下,您有来自

SpecialTest
YourNormalFeatureClass
的测试。这意味着您不需要运行
YourNormalFeatureClass
测试,而只运行
SpecialTest
测试。

如果 SpecFlow 允许您自定义代码生成过程,所有这些问题都将很容易解决。这样您就可以通过生成的代码公开

ITestOutputHelper
。步骤内的消耗是相同的。


1
投票

这可能是 SpecFlow 的新补充,因为这个问题是在 6 年前提出的,但是 TechTalk.SpecFlow.Infrastruct.ISpecFlowOutputHelper 应该可以解决您的问题。注入它并以与 xUnit 的 ITestOutputHelper 大致相同的方式使用它,例如

[Binding]
public class SomeSteps
{
    private readonly ISpecFlowOutputHelper output;

    public SomeSteps(ISpecFlowOutputHelper output)
    {
        this.output = output;
    }

    [When(@"I write some debug info")]
    public void WhenIWriteSomeDebugInfo()
    {
        this.output.WriteLine("Hello world!");
    }
}

0
投票

在并行运行框架下,你不能再使用静态的 ScenarioContext,但你可以使用:

var console= _scenarioContext.ScenarioContainer.Resolve<ISpecFlowOutputHelper>();

参考:https://docs.specflow.org/projects/specflow/en/latest/Execution/Parallel-Execution.html#xunit-configuration

© www.soinside.com 2019 - 2024. All rights reserved.