Srinivas Miriyala's Blog


Thursday, March 26, 2015

Unit Testing the Console Applications with ReadLine and WriteLine methods

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Enter your name.");
        string name = Console.ReadLine();
        Console.WriteLine("Hello, {0}.", name);
        Console.WriteLine("Type a message.");
        string message = Console.ReadLine();
        Console.WriteLine("You wrote: {0}", message);
    }
}




[TestMethod]
public void RunMain()
{
    using (StringWriter sw = new StringWriter())
    {
        Console.SetOut(sw);
 
        using (StringReader sr = new StringReader(string.Format("Mark{0}Ploeh{0}",
            Environment.NewLine)))
        {
            Console.SetIn(sr);
 
            Program.Main(new string[] { });
 
            string expected = string.Format(
                "Enter your name.{0}Hello, Mark.{0}Type a message.{0}You wrote: Ploeh{0}",
                Environment.NewLine);
            Assert.AreEqual<string>(expected, sw.ToString());
        }
    }
}




For more details :
http://blogs.msdn.com/b/ploeh/archive/2006/10/21/consoleunittesting.aspx