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!
Actually it's the error output that needs to be redirected...
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);
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With