单元测试控制台C#应用程序的最佳方法 [英] Best way to unit test console c# app
问题描述
我有一个简单的控制台应用程序.它用一个普通的main解雇,整个程序都驻留在main中.它使用命令行解析器库.然后,我在解决方案中有了第二个项目,其中包含该应用程序的单元测试.但是我似乎找不到从测试中启动主程序进程的好方法.我当前用于实际启动该过程的代码如下所示.
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;
...
我尝试设置
process.StartInfo.WorkingDirectory
到
AppDomain.CurrentDomain.BaseDirectory
和
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.
我也尝试过运行Program.Main,但是感觉很不对:)
I also tried Running Program.Main but that just feels so wrong :)
推荐答案
我建议将您的应用程序重组为:
I would suggest restructuring your application into:
-
Program
-解析参数的入口,创建一个Settings
实例 -
设置
-应用程序的设置(根据喜好重命名) -
BusinessClass
-(绝对重命名!)实际的工作,它接受Settings
实例
Program
- an entry point which parses the arguments, creating aSettings
instanceSettings
- settings for the application (rename according to taste)BusinessClass
- (definitely rename!) the actual work, which accepts aSettings
instance
现在您可以分别测试事物:
Now you can test things separately:
- 将解析测试为
Settings
,即您是否正确使用了解析器库 - 您的业务逻辑(单元测试将在其中创建
Settings
的相应实例)
- 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.
这篇关于单元测试控制台C#应用程序的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!