Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect console output for just one method

Tags:

c#

output

console

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...

like image 789
thomasb Avatar asked Sep 29 '14 08:09

thomasb


2 Answers

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);
like image 87
Adriano Repetti Avatar answered Nov 19 '22 11:11

Adriano Repetti


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");
like image 30
Matthew Watson Avatar answered Nov 19 '22 10:11

Matthew Watson