Unit Testing a Console Application inside Visual Studio

console-applicationunit testingvisual studio 2010

I have a Test Project in Visual Studio I'd like to use to test my console application with (in the same solution).

I'm trying to set up tests which call the console app with specific parameters, and compare the actual output with what I expect, then do my usual Assert statements to appropriately pass/fail the test.

The best way to do this, that I can come up with, is to execute the app exe with System.Diagnostics.Process inside the unit test. This works. I can read the output, and all is well.

The problem I'm having is when I want to set a breakpoint inside the console app code, so I can do some debugging. Since Process kicked off the console app, Visual Studio isn't watching the console app, so it won't break. There's nothing like "Wait for a request from an external application" like there is with Web Apps, and I understand why, but that's basically what I'm looking for.

So my question is, is there any way to set up these unit tests inside Visual Studio, where I can still debug the console app? The only workaround I can think of is setting the Start Action on the console application to start an external program, which would call MSTest.exe, and run the appropriate unit tests that way. But this seems like a problem which I'm just thinking about it wrong, and there actually is a much more obvious solution.

Best Answer

Make your console application as thin as possible, and move all business logic to domain classes. E.g.

class Program
{
    static void Main(string[] args)
    {
       Foo foo = new Foo(args);
    }
}

After that you can easily write unit tests for your Foo class.