mercredi 29 juillet 2015

Testing console in and out console application in C#

I have a problem with testing "Console in" and "Console out" in a C# console application.

If I use Console.WriteLine and Console.ReadLine I can use NUnit framework to test the application, but if I use a helper class for in and output to console I cannot get it to work.

The helper class is http://ift.tt/1Sh0aAL and uses a BufferedStream to write to the Console, but I cannot get my test to read it...

It uses A StreamReader for "Console in" but I get a "NoMoreTokenException" which I guess that it don't get any input...

I would like to use the helper class but I cannot test with it...

Ex: Testcase:

    [Test]
    public void test_hello_world ()
    {
        using (var sw = new StringWriter ()) {              
            Console.SetOut (sw);
            using (var sr = new StringReader ("Start")) {
                Console.SetIn (sr);
                MainClass.Main(new string[]{});
                string expected = "Hello World!\n";
                Assert.AreEqual (sw.ToString (), expected);
            }
        }
    }

Ex: Code that work:

    string line = "";
    if (Console.ReadLine().Equals("Start"))
        line = "Hello World!";
    else
        line = "No such luck!";
    Console.WriteLine (line);

Ex: Code that don't work:

        string line = "";
        Scanner sc = new Scanner ();
        if (sc.Next ().Equals ("Start"))
            line = "Hello World!";
        else
            line = "No such luck!";
        BufferedStdoutWriter outWritter = new BufferedStdoutWriter ();
        outWritter.WriteLine (line);
        outWritter.Flush ();

Anyone having any insight on how to solve this?

Aucun commentaire:

Enregistrer un commentaire