C#单元测试(Nunit)控制台应用程序的主要方法? [英] C# Unit Testing(Nunit) the Main method of a console app?

查看:87
本文介绍了C#单元测试(Nunit)控制台应用程序的主要方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对控制台应用程序Main方法的单元测试有疑问。标准签名是

I have a question on unit testing the Main method of a console app. The standard signature is

  public static void Main(string[] args)

我希望能够进行测试以确保仅传入1个参数。如果传入多个参数,则我希望测试失败。

I want to be able to test to ensure that only 1 parameter is passed in. If more than one parameter is passed in that i want the test to fail.

我认为我不能以最小起订量作为静态方法来模拟它。

I don't think i can mock this with MOQ as its a static method.

任何人都有有经验吗?

有任何想法吗?

谢谢

推荐答案

在您的方案中没有什么可嘲笑的。静态 Program.Main 是一种方法,您可以通过调用它来对其进行测试。

There is nothing to mock in your scenario. Static Program.Main is a method just as any other and you test it as such -- by invoking it.

静态无效方法的问题在于,您只能验证它是否抛出异常或与输入参数(或最终与其他静态成员)进行交互。由于在 string [] 上没有任何可与之交互的内容,因此您可以测试以前的情况。

The issue with static void method is that you can only verify whether it throws exception or interacts with input argument (or other static members, eventually). Since there is nothing to interact with on string[] you can test former case.

但是,声音更清晰方法是委托 Main 中包含的 all 逻辑来分离组件并对其进行测试。不仅可以让您彻底测试输入参数处理逻辑,而且可以将 Main 简化为或多或少的方式:

However, a more sound approach is to delegate all logic contained in Main to separate component and test it instead. Not only this allows you to test your input argument handling logic thoroughly but also simplifies Main to more or less this:

public static void Main(string[] args)
{
    var bootstrapper = new Bootstrapper();
    bootstrapper.Start(args);
}

这篇关于C#单元测试(Nunit)控制台应用程序的主要方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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