Created
June 25, 2017 22:35
-
-
Save kenegozi/e0c67ca2e014536b955dfbb27a310ea8 to your computer and use it in GitHub Desktop.
Capturing console output in Xunit 2 tests
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; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using Xunit.Abstractions; | |
namespace MagicalUnicorns { | |
public class XunitConsoleForwarder : TextWriter { | |
private readonly ITestOutputHelper output; | |
private IList<char> line = new List<char>(); | |
public XunitConsoleForwarder(ITestOutputHelper output) { | |
this.output = output; | |
} | |
public override Encoding Encoding => Console.Out.Encoding; | |
public override void Write(char value) { | |
if (value == '\n') { | |
FlushLine(); | |
line = new List<char>(); | |
return; | |
} | |
line.Add(value); | |
} | |
protected override void Dispose(bool disposing) { | |
if (line.Count > 0) { | |
FlushLine(); | |
} | |
base.Dispose(disposing); | |
} | |
private void FlushLine() { | |
if (line.Count > 0 && line.Last() == '\r') { | |
line.RemoveAt(line.Count - 1); | |
} | |
output.WriteLine(new string(line.ToArray())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just what I was looking for: a magical unicorn 😄