Best way to unit test console c# app

▼魔方 西西 提交于 2019-12-30 01:19:06

问题


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 :)


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12104429/best-way-to-unit-test-console-c-sharp-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!