Testing the console in and out of the console application in C #

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

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

The helper class is https://open.kattis.com/download/Kattio.cs and uses BufferedStream to write to the console, but I cannot get my test to read it ..

It uses StreamReader for "Console in", but I get a "NoMoreTokenException", which I think does not get any input ...

I would like to use a helper class, but I cannot check with it ...

Example: 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); } } } 

Example: code that works:

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

Ex: code that doesn'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 (); 

Does anyone know how to solve this?

+4
source share
1 answer

As @juharr mentions in a comment, calling Console.OpenStandardInput will reset the input stream. Thus, you need to make a helper class for console threads. (Only if you are allowed to change the implementation).

First, the Tokenizer class can be updated to use the console Reader as a TextReader text editor:

 public class Tokenizer { string[] tokens = new string[0]; private int pos; // StreamReader reader; Changed to TextReader TextReader reader; public Tokenizer(Stream inStream) { var bs = new BufferedStream(inStream); reader = new StreamReader(bs); } public Tokenizer() { // Add a default initializer as Console Input stream reader. reader = Console.In; } // ...... Rest of the code goe here............... // ..................... } 

Also modify the buffer output entry as follows:

Updated . The constructor will also accept other threads.

 public class BufferedStdoutWriter { public TextWriter Writer; public BufferedStdoutWriter() { // Use default writer as console output writer this.Writer = Console.Out; } public BufferedStdoutWriter(Stream stream) { Writer = new StreamWriter(new BufferedStream(stream)); } public void Flush() { Writer.Flush(); } public void Write<T>(T value) { Writer.Write(value); } public void WriteLine<T>(T value) { Writer.WriteLine(value); } } 

Similarly, more functions can be implemented if necessary.

Your test will now pass successfully for EX: Code that doesn't work .

+5
source

All Articles