Last active
December 8, 2022 09:04
-
-
Save jmcd/aed8e301d61529010d6b618b5a04924f to your computer and use it in GitHub Desktop.
Capture `Console.Out` 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 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); | |
} | |
} |
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 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