Skip to content

Instantly share code, notes, and snippets.

@kenegozi
Created June 25, 2017 22:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenegozi/e0c67ca2e014536b955dfbb27a310ea8 to your computer and use it in GitHub Desktop.
Save kenegozi/e0c67ca2e014536b955dfbb27a310ea8 to your computer and use it in GitHub Desktop.
Capturing console output in Xunit 2 tests
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()));
}
}
}
@sfmskywalker
Copy link

sfmskywalker commented Oct 19, 2020

Just what I was looking for: a magical unicorn 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment