Created
January 20, 2023 20:00
-
-
Save thargenediad/114f1323632b8d49989b5f02afafb7b5 to your computer and use it in GitHub Desktop.
Capture `Console.Out` and Trace Logs in an XUnit `ITestOutputHelper`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class XUnitOutputDemo : IDisposable | |
{ | |
private readonly TextWriter consoleOut; | |
private readonly XUnitTestOutputHelperToTextWriterConverter outAdapter; | |
public XUnitOutputDemo(ITestOutputHelper output) | |
{ | |
consoleOut = Console.Out; | |
converter = new XUnitTestOutputHelperToTextWriterConverter(output); | |
Console.SetOut(converter); | |
Trace.Listeners.Add(new TextWriterTraceListener(converter)); | |
} | |
public void Dispose() | |
{ | |
Console.SetOut(consoleOut); | |
outAdapter.Dispose(); | |
} | |
[Fact] | |
public void WriteSomeThings() | |
{ | |
Console.WriteLine("printed"); | |
Console.Write("also printed"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text; | |
using Xunit.Abstractions; | |
public class XUnitTestOutputHelperToTextWriterConverter : TextWriter | |
{ | |
ITestOutputHelper _output; | |
public XUnitTestOutputHelperToTextWriterConverter(ITestOutputHelper output) | |
{ | |
_output = output; | |
} | |
public override Encoding Encoding | |
{ | |
get { return Encoding.Default; } | |
} | |
public override void WriteLine(string? message) | |
{ | |
_output.WriteLine(message); | |
} | |
public override void WriteLine(string format, params object?[] args) | |
{ | |
_output.WriteLine(format, args); | |
} | |
public override void Write(string? value) | |
{ | |
_output.WriteLine(value); | |
} | |
public override void Write(char value) | |
{ | |
throw new NotSupportedException("This text writer only supports WriteLine(string) and WriteLine(string, params object[])."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment