c# - 使用 dotnet core 1.1 和 xunit 单元测试显示输出?

标签 c# unit-testing .net-core visual-studio-2017 xunit

多年来,我发现创建单元测试是一种在 Visual Studio 中试用代码的 super 简单方法。通过创建 Visual C#/.NET Core/Unit Test Project (.NET Core) 项目,我能够在 VS 2017 中使用 .NET core 1.1 进行相同类型的单元测试,然后添加xunitxunit.runner.visualstudio nuget 包。

唯一的问题是,当运行测试以查看我写入控制台的内容时,我不再看到“输出”链接。我可以改用 System.Diagnostics 包中的 Trace.WriteLine 并在 Visual Studio 的 Output 窗口中查看输出,但看到的是输出与每个测试运行关联起来更容易、更有用。

有没有办法让它与我的设置一起显示,或者我可以使用不同的设置?

编辑

@ilya 的解决方案有效,但我必须重新编写所有测试,删除 [TestClass] 并将 [TestMethod] 替换为 [Fact],而且我不能再右键单击并运行单个测试方法,这样做似乎可以运行类中的所有测试方法...

最佳答案

推荐的 xUnit 捕获输出的方法是使用 ITestOutputHelper:

public class BaseTestClass
{
    protected ITestOutputHelper Output { get; }

    public BaseTestClass(ITestOutputHelper output)
    {
        Output = output;
    }

    public void WriteLine(string str)
    {
        Output.WriteLine(str ?? Environment.NewLine);
    }
}

public class MyTestClass : BaseTestClass
{
    public MyTestClass(ITestOutputHelper output) : base(output) {}

    [Fact]
    public void MyTest()
    {
        WriteLine("foo");
    }
}

查看文档:Capturing Output .

If you used xUnit.net 1.x, you may have previously been writing output to Console, Debug, or Trace. When xUnit.net v2 shipped with parallelization turned on by default, this output capture mechanism was no longer appropriate; it is impossible to know which of the many tests that could be running in parallel were responsible for writing to those shared resources. Users who are porting code from v1.x to v2.x should use one of the two new methods instead.

关于c# - 使用 dotnet core 1.1 和 xunit 单元测试显示输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44013959/

相关文章:

c# - asp.net中如何在Lucene.net中进行模糊搜索?

c# - 没有正确计算体积

android - 在 Intellij 的 Android 单元测试期间记录 java.lang.RuntimeException : Stub

ubuntu - nginx上的多个网络核心应用程序同一个域

.net - 针对多个框架的项目上的 "dotnet build"仅构建 "netstandard2.0"并且不生成 nupkg 文件

azure - 根据区域禁用/启用 Azure 功能

c# - iOS 设备上的表单应用程序在启动屏幕后崩溃

c# - 安装 sql server 2014 时出现 netfx3 错误?

unit-testing - 你在哪里存储可重用的模拟?

c# - 为具有 protected 对象 C# 的代码编写单元测试的好方法是什么(使用 NMock 和 NUnit 框架)