Skip to content

Instantly share code, notes, and snippets.

@jmcd
Last active December 8, 2022 09:04
Show Gist options
  • Save jmcd/aed8e301d61529010d6b618b5a04924f to your computer and use it in GitHub Desktop.
Save jmcd/aed8e301d61529010d6b618b5a04924f to your computer and use it in GitHub Desktop.
Capture `Console.Out` in an XUnit `ITestOutputHelper`
public class TestOutputHelperTextWriterAdapter : TextWriter
{
private readonly ITestOutputHelper output;
private string currentLine = "";
public TestOutputHelperTextWriterAdapter(ITestOutputHelper output)
{
this.output = output;
}
public override Encoding Encoding { get; }
public bool Enabled { get; set; } = true;
public override void Write(char value)
{
if (!Enabled) { return; }
if (value == '\n')
{
WriteCurrentLine();
}
else
{
currentLine += value;
}
}
private void WriteCurrentLine()
{
output.WriteLine(currentLine);
currentLine = "";
}
protected override void Dispose(bool disposing)
{
if (currentLine != "") { WriteCurrentLine(); }
base.Dispose(disposing);
}
}
public class OutputDemo : IDisposable
{
private readonly TextWriter origConsoleOut;
private readonly TestOutputHelperTextWriterAdapter outAdapter;
public OutputDemo(ITestOutputHelper output)
{
origConsoleOut = Console.Out;
outAdapter = new TestOutputHelperTextWriterAdapter(output);
Console.SetOut(outAdapter);
}
public void Dispose()
{
Console.SetOut(origConsoleOut);
outAdapter.Dispose();
}
[Fact]
public void WriteSomeThings()
{
Console.WriteLine("printed");
outAdapter.Enabled = false;
Console.WriteLine("not printed");
outAdapter.Enabled = true;
Console.Write("also printed");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment