Creating An Attribute for Redirecting Console Input & Output
While writing my Essential C# (Addison-Wesley), I created many console applications. Unit testing has been rather cumbersome. I decided to create an attribute that can redirect the console input and output so that I can supply various inputs and then test the output.
Test expected output
Provide automated input
In addition, I wanted ConsoleOutputExpected to support wild-cards, regular expressions, and straight string comparison.
Use regular expressions in the expected console output
Use wild-cards in the expected console output
Anyway, following the instructions I derived from MbUnit.Core.Framework.DecoratorPatternAttribute and implemented the Execute() method as follows:
In summary, the process was relatively simple, and I was pleased with the results, with two exceptions:
- The C# string literal syntax is funky when text spans lines. The problem is that code is indented, but the text itself can’t be because it is taken literally. This makes for rather peculiar code. I wish there was an elegant way to keep indentation within the source code but not the literal.
- The new Console methods in .NET 2.0 like System.Console.CursorTop/Left and System.Console.SetCursorPosition() cannot be redirected. It always throws an invalid handle exception. This makes unit testing these methods beyond reasonable. I posted a bug about this problem in the hopes that Microsoft would fix the issue before release.
Download the source code.