Reputation: 4836
I'm writing test code for the following method:
public static void PrintAll<T>(this IEnumerable<T> collection)
{
foreach (T item in collection)
{
Console.Write(item.ToString());
}
}
So essentially what I think needs to be done is that I can fill an array with random data, output it using this method, store it in a stream/collection and then output it using the standard foreach loop and compare the two.
I understand that Console.Write()
doesn't actually write to the console it writes to my application's standard output.
I know how to redirect this for other Process
objects but have no clue how to redirect my own application's standard output, any ideas?
Upvotes: 2
Views: 872
Reputation: 1237
You can use Console.SetOut to set the output of the console temporarily to a string.
For example:
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
// Save the standard output.
TextWriter tmp = Console.Out;
Console.SetOut(sw);
// Code which calls Console.Write
Console.SetOut(tmp);
string actual = sb.ToString();
Remember to dispose the StringWriter
object.
Upvotes: 3