9

I have here a bunch of unit tests. One of them expects the code to do nothing because the arguments parsing should not work.

Unfortunately, the arguments parsing library I'm using forces Console.Write() in this case, and now my unit tests output is full of the library's messages, which makes it hard to read.

Is there a way to redirect the standard console output to nothing (or a temp file or whatever) before calling this method, and then redirecting it back to the standard output once it's finished ?

Thanks!

Update

Actually it's the error output that needs to be redirected...

thomasb
  • 5,816
  • 10
  • 57
  • 92

2 Answers2

17

Yes, you can temporary replace output stream with a custom one. It can be done with Console.SetOut() method. More or less (adapting to your actual code, see also comments):

// We're not interested in its output, a NULL fake one may also work (better)
Console.SetOut(new StringWriter());

// Your code here...

// Now you have to restore default output stream
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);

UPDATE: according to your update (redirect of standard error stream) you simply need to replace *Out with *Error:

Console.SetError(new StringWriter());

// Your code here...

var standardError = new StreamWriter(Console.OpenStandardError());
standardError.AutoFlush = true;
Console.SetError(standardError);
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
13

You can create a TextWriter that does nothing:

public sealed class NulTextWriter: TextWriter
{
    public override Encoding Encoding
    {
        get
        {
            return Encoding.UTF8;
        }
    }
}

Then you can set and restore the console output like so:

Console.WriteLine("Enabled");

var saved = Console.Out;
Console.SetOut(new NulTextWriter());
Console.WriteLine("This should not appear");

Console.SetOut(saved);
Console.WriteLine("Restored");

You can use the same approach for the console's error output:

Console.Error.WriteLine("Enabled");

var saved = Console.Error;
Console.SetError(new NulTextWriter());
Console.Error.WriteLine("This should not appear");

Console.SetError(saved);
Console.Error.WriteLine("Restored");
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • this one is perfect, specially for third party applications throwing messages in our build server during tests.. – Alan Jun 25 '18 at 16:35
  • Nice reusing of the existing writer and output stream! For temporary output redirection, this seems more lightweight than opening another output stream. – CodeFox Dec 05 '18 at 07:38