From 27ea990671fb3e2010daf59aeed95e6c83ae50a4 Mon Sep 17 00:00:00 2001 From: Jon Fuller Date: Tue, 17 Dec 2019 16:10:17 -0500 Subject: [PATCH] Adds option for setting the output TextWriter * adds the option to the options class * defaults the option to Console.Out * Write method now uses Options.OutputTo instead of Console --- ConsoleTables.Tests/ConsoleTableTest.cs | 33 +++++++++++++++++++++++++ src/ConsoleTables/ConsoleTable.cs | 14 ++++++++--- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/ConsoleTables.Tests/ConsoleTableTest.cs b/ConsoleTables.Tests/ConsoleTableTest.cs index 71b85e0..10faab1 100644 --- a/ConsoleTables.Tests/ConsoleTableTest.cs +++ b/ConsoleTables.Tests/ConsoleTableTest.cs @@ -1,4 +1,6 @@ +using System; using System.Collections.Generic; +using System.IO; using Xunit; namespace ConsoleTables.Tests @@ -86,6 +88,37 @@ public void NumberShouldBeRightAlignedOnMarkDown() ", table); } + [Fact] + public void OutputShouldDefaultToConsoleOut() + { + var users = new List + { + new User { Name = "Alexandre" , Age = 36 } + }; + + var table = ConsoleTable.From(users); + + Assert.Equal(table.Options.OutputTo, Console.Out); + } + + [Fact] + public void OutputShouldGoToConfiguredOutputWriter() + { + var users = new List + { + new User { Name = "Alexandre" , Age = 36 } + }; + + var testWriter = new StringWriter(); + + ConsoleTable + .From(users) + .Configure(o => o.OutputTo = testWriter) + .Write(); + + Assert.NotEmpty(testWriter.ToString()); + } + class User { public string Name { get; set; } diff --git a/src/ConsoleTables/ConsoleTable.cs b/src/ConsoleTables/ConsoleTable.cs index d687996..5a405b3 100644 --- a/src/ConsoleTables/ConsoleTable.cs +++ b/src/ConsoleTables/ConsoleTable.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Reflection; using System.Text; @@ -241,16 +242,16 @@ public void Write(Format format = ConsoleTables.Format.Default) switch (format) { case ConsoleTables.Format.Default: - Console.WriteLine(ToString()); + Options.OutputTo.WriteLine(ToString()); break; case ConsoleTables.Format.MarkDown: - Console.WriteLine(ToMarkDownString()); + Options.OutputTo.WriteLine(ToMarkDownString()); break; case ConsoleTables.Format.Alternative: - Console.WriteLine(ToStringAlternative()); + Options.OutputTo.WriteLine(ToStringAlternative()); break; case ConsoleTables.Format.Minimal: - Console.WriteLine(ToMinimalString()); + Options.OutputTo.WriteLine(ToMinimalString()); break; default: throw new ArgumentOutOfRangeException(nameof(format), format, null); @@ -282,6 +283,11 @@ public class ConsoleTableOptions /// Enable only from a list of objects /// public Alignment NumberAlignment { get; set; } = Alignment.Left; + + /// + /// The to write to. Defaults to . + /// + public TextWriter OutputTo { get; set; } = Console.Out; } public enum Format