在Visual Studio中对控制台应用程序进行单元测试 [英] Unit Testing a Console Application inside Visual Studio

查看:69
本文介绍了在Visual Studio中对控制台应用程序进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Visual Studio中有一个测试项目,我想用它来测试我的控制台应用程序(在同一解决方案中)。

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

我正在尝试设置测试以特定的参数调用控制台应用程序,然后将实际输出与我的期望值进行比较,然后执行我通常的Assert语句以适当地通过/失败测试。

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.

我能想到的最好的方法是在单元测试中使用System.Diagnostics.Process执行应用程序exe。这可行。我可以读取输出了,一切都很好。

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.

我遇到的问题是想在控制台应用程序代码中设置断点时,我可以这样做一些调试。由于Process启动了控制台应用程序,因此Visual Studio不在监视该控制台应用程序,因此它不会中断。像Web Apps一样,没有什么比等待来自外部应用程序的请求更容易理解了,但这基本上就是我要寻找的东西。

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.

所以我的问题是,有什么方法可以在Visual Studio中设置这些单元测试,但仍可以在其中调试控制台应用程序?我能想到的唯一解决方法是在控制台应用程序上设置启动操作以启动外部程序,该程序将调用MSTest.exe,并以这种方式运行适当的单元测试。但这似乎是一个问题,我只是在想错了,实际上还有一个很多更明显的解决方案。

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.

推荐答案

使控制台应用程序尽可能精简,并将所有业务逻辑移至域类。例如,

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);
    }
}

之后,您可以轻松地为Foo编写单元测试课。

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

这篇关于在Visual Studio中对控制台应用程序进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆