Skip to content

Instantly share code, notes, and snippets.

@jindeveloper
Forked from asierba/unittestconsole.cs
Created November 10, 2019 15:24
Show Gist options
  • Save jindeveloper/b733ce929042fe30ac4f61ef2ddd2967 to your computer and use it in GitHub Desktop.
Save jindeveloper/b733ce929042fe30ac4f61ef2ddd2967 to your computer and use it in GitHub Desktop.
How to mock console in unit tests
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("What's your name?");
var name = Console.ReadLine();
Console.WriteLine(string.Format("Hello {0}!!", name));
}
[Test]
public void something()
{
var output = new StringWriter();
Console.SetOut(output);
var input = new StringReader("Somebody");
Console.SetIn(input);
Program.Main(new string[] { });
Assert.That(output.ToString(), Is.EqualTo(string.Format("What's your name?{0}Hello Somebody!!{0}", Environment.NewLine)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment