首页 > 解决方案 > 如何在 SpecFlow 中使用 Nlog 登录?

问题描述

SpecFlow 将其输出写入控制台,如下所示:

Given the "TestOperator" user is logged in
-> done: WebUserSteps.GivenTheUserIsLoggedIn("TestOperator", "") (9.5s)

我们如何让它使用 NLog 来配置它应该写入的位置?

有了这个:

public class CustomListener : ITraceListener
{
    private Logger Log = LogManager.GetLogger("SPECFLOW");

    public void WriteTestOutput(string message)
    {
        Log.Trace(message);
    }

    public void WriteToolOutput(string message)
    {
        Log.Trace(message);
    }
}

[Binding]
public class ScenarioContextInitializer 
{
    private readonly IObjectContainer _container;

    public ScenarioContextInitializer(ScenarioContext scenarioContext)
    {
        _container = (scenarioContext ?? throw new ArgumentNullException(nameof(scenarioContext))).ScenarioContainer;
    }

    [Before]
    protected void Load()
    {
        _container.RegisterTypeAs<CustomListener, ITraceListener>();
    }
}

它没有用。我知道可以添加插件,但这似乎开销太大。

我们还使用ObjectivityLtd Test.Automation扩展。

它通过SpecFlow.xUnit生成的 xunit 测试工作

标签: c#nlogspecflowxunit

解决方案


我用这个解决方法在我的框架中做了类似的事情:

  • 添加钩子 [AfterStep],使用步骤的名称调用 Console.WriteLine() [或您的记录器],如果通过与否(如果测试错误!= null,这意味着失败,通过)
    请注意,这很完美在并行执行中。(正确的输出到每个测试)

这是示例: https ://github.com/LirazShay/SpecFlowDemo/blob/master/src/SpecFlowDemo/Hooks.cs

像这样的东西:

 [AfterStep]
 public void LogStepResult()
        {
          string stepText = StepContext.StepInfo.StepDefinitionType + " " + StepContext.StepInfo.Text;
          Console.WriteLine(stepText);
          var stepTable = StepContext.StepInfo.Table;
          if (stepTable != null && stepTable.ToString() != "") Console.WriteLine(stepTable);
          var error = ScenarioContext.TestError;
          Console.WriteLine(error != null ? "-> error: " + error.Message : "-> done.");
        }

推荐阅读