因为Console.WriteLine
,这是一种方法(可能有更好的方法,但这对我有用):
public class ConsoleOutputHelper : TextWriter, ITestOutputHelper
{
private readonly ITestOutputHelper _helper;
public ConsoleOutputHelper(ITestOutputHelper helper) => _helper = helper;
public override void WriteLine(string? message)
{
try
{
_helper.WriteLine(message);
}
catch (InvalidOperationException ex) when (ex.Message.Contains("no currently active test"))
{
}
}
public override void WriteLine(string format, params object?[] args) =>
_helper.WriteLine(format, args);
public override Encoding Encoding => new UTF8Encoding();
}
...然后,在您的测试构造函数中:
public MyTests(ITestOutputHelper helper) =>
Console.SetOut(new ConsoleOutputHelper(helper));
...然后,在您正在测试的代码中
Console.Out.WriteLine("Beginning something...");
更新
Trace.WriteLine
在生产代码中可能更好。
设置看起来像这样(需要添加和删除跟踪侦听器):
public class MyTests : IDisposable
{
private readonly TraceOutputHelper _traceOutputHelper;
public MyTests(ITestOutputHelper helper)
{
_traceOutputHelper = new TraceOutputHelper(helper);
Trace.Listeners.Add(_traceOutputHelper);
}
public void Dispose() => Trace.Listeners.Remove(_traceOutputHelper);
...并且与上面TraceOutputHelper
非常相似ConsoleOutputHelper
:
public class TraceOutputHelper : TextWriterTraceListener, ITestOutputHelper
{
private readonly ITestOutputHelper _helper;
public TraceOutputHelper(ITestOutputHelper helper) => _helper = helper;
public override void WriteLine(string? message)
=> _helper.WriteLine(message);
public void WriteLine(string format, params object[] args) => _helper.WriteLine(format, args);
}