多年来,我发现创建单元测试是一种在 Visual Studio 中试用代码的 super 简单方法。通过创建 Visual C#/.NET Core/Unit Test Project (.NET Core)
项目,我能够在 VS 2017 中使用 .NET core 1.1 进行相同类型的单元测试,然后添加xunit
和 xunit.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 toConsole
,Debug
, orTrace
. WhenxUnit.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/