When you need to test console output, use TestConsole from Spectre.Console.Testing.
Accept IAnsiConsole
To enable testing, accept IAnsiConsole as a parameter.
// Instead of: AnsiConsole.MarkupLine("[green]Hello![/]");
// Use the injected console:
console.MarkupLine("[green]Hello![/]");
Structure for Testability
To test code, pass TestConsole instead of the real console.
// Production code calls with the real console:
PrintGreeting(AnsiConsole.Console, "World");
// Test code would call with TestConsole:
// var testConsole = new TestConsole();
// PrintGreeting(testConsole, "Test");
// Assert.Contains("Hello, Test!", testConsole.Output);
Write Testable Methods
To make methods testable, have them accept IAnsiConsole.
console.MarkupLine($"[green]Hello, {name}![/]");
Test Prompts
To test prompts, queue input with console.Input.PushTextWithEnter().
return console.Prompt(
new TextPrompt<string>("What's your name?"));
See Also
- Spectre.Console.Testing - Testing package