我这里有一堆单元测试。其中之一希望代码不执行任何操作,因为参数解析应该不起作用。
不幸的是,在这种情况下,我正在使用的参数解析库强制 Console.Write()
,现在我的单元测试输出充满了库的消息,这使得它难以阅读。
有没有办法在调用此方法之前将标准控制台输出重定向到空(或临时文件或其他),然后在完成后将其重定向回标准输出?
谢谢!
更新
其实是需要重定向的错误输出...
最佳答案
是的,您可以临时用自定义流替换输出流。可以用 Console.SetOut() 来完成方法。或多或少(根据您的实际代码进行调整,另请参阅注释):
// 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);
更新:根据您的更新(标准错误 流的重定向),您只需将*Out
替换为*Error
:
Console.SetError(new StringWriter());
// Your code here...
var standardError = new StreamWriter(Console.OpenStandardError());
standardError.AutoFlush = true;
Console.SetError(standardError);
关于c# - 仅为一种方法重定向控制台输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26095529/