Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to unit test console c# app

I have a simple console app. It's fired of with a normal main and the entire program recides in main. It uses the Command Line Parser Library. Then I have a second project in the solution containing unit tests for the application. But I don't seem to find a good way to start processes of the main program from the tests. My current code for actually start the process looks something like this.

...

process = new Process();
process.StartInfo.FileName = "FooBar";
process.StartInfo.Arguments = arguments;

// use it to start from testing environment
process.StartInfo.UseShellExecute = false;

// redirect outputs to have it in testing console
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;

...

I have tried setting

process.StartInfo.WorkingDirectory

to

AppDomain.CurrentDomain.BaseDirectory

and

Environment.CurrentDirectory;

But do I have to specify the entire relative path for the console applications executable or is there a refined way of starting processes of the "tested" application? First I had my tests as a class in the "main" program and then it worked just fine. The issues started when I moved the tests to their own project. That's why I suspect a path being the issue or something of that nature.

I also tried Running Program.Main but that just feels so wrong :)

like image 386
inquam Avatar asked Aug 24 '12 06:08

inquam


2 Answers

I would suggest restructuring your application into:

  • Program - an entry point which parses the arguments, creating a Settings instance
  • Settings - settings for the application (rename according to taste)
  • BusinessClass - (definitely rename!) the actual work, which accepts a Settings instance

Now you can test things separately:

  • Test the parsing into Settings, i.e. are you using the parser library correctly
  • Your business logic, where the unit tests create appropriate instances of Settings

If possible, you should separate your business logic into separate classes for separate concerns of course, and test each separately. We don't really know enough to make concrete suggestions here.

like image 145
Jon Skeet Avatar answered Oct 05 '22 19:10

Jon Skeet


I don't know why running Program.Main feels wrong for you.
You're not supposed to unit-test the console mechanism.. only your program's logic, which you can easily do this way.

like image 44
Jony Adamit Avatar answered Oct 05 '22 20:10

Jony Adamit