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

时间:2016-04-01 19:02:45

标签: c# specflow xunit xunit2

不幸的是我在本地传递了一个Specflow测试,但它在VSO Build vNext服务器上失败了,我真的需要在测试运行期间看到详细的信息,这样我才能弄清楚发生了什么。

但是我很难尝试将ITestOutputHelper注入像这样的Specflow绑定

public SomeSteps(ITestOutputHelper outputHelper)

但是Specflow抱怨消息

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

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

2 个答案:

答案 0 :(得分: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个副本,因为您继承了旧测试。因此,在这种情况下,您可以使用SpecialTestYourNormalFeatureClass进行测试。这意味着您不需要运行YourNormalFeatureClass测试,只需运行SpecialTest测试。

如果SpecFlow允许您自定义代码生成过程,所有这些都将很容易解决。这样您就可以通过生成的代码公开ITestOutputHelper。从步骤中消耗它将是相同的。

答案 1 :(得分:0)

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

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