2

I have an app which can be used like:

type file.txt|app.exe -i

I.e. my app will read the data from file.txt.

And now I want to write some tests to make sure app works well with some special data in file.txt.

How to organize this?

My app reads input like

input = Console.In.ReadToEnd();

On the simple tests without reading data I was simply using App class like:

using(App app = new App())
{
  result = app.Run(args)
}
if (result != 0)
Assert.Fail("Failed");
Ksice
  • 3,277
  • 9
  • 43
  • 67
  • Does this answer your question? [C# unit test for a method which calls Console.ReadLine()](https://stackoverflow.com/questions/3161341/c-sharp-unit-test-for-a-method-which-calls-console-readline) – Artur INTECH Feb 15 '23 at 08:46

1 Answers1

4

You can replace the console input with your own object, say StringReader, and provide any input you want to it:

var oldIn = Console.In;
try
{
    Console.SetIn(new StringReader("some input"));

    using (App app = new App())
    {
        // input = Console.In.ReadToEnd(); happens here
        result = app.Run(args);
    }

    if (result != 0)
    {
        Assert.Fail("Failed");
    }
}
finally
{
    Console.SetIn(oldIn);
}
Andrei
  • 55,890
  • 9
  • 87
  • 108