繁体   English   中英

主要方法的C#单元测试-操纵命令行参数-Microsoft Visual Studio测试工具

[英]C# Unit Test for Main Method - Manipulating Command Line Arguments - Microsoft Visual Studio Test Tools

使用Visual Studio,我正在为已经使用.Net framework 2.0编写的程序编写单元测试。 除Main(应用程序的入口)测试外,所有常规单元测试都可以正常工作。 声明程序的Main方法时,不传递任何String []作为参数。 该程序使用关联对象中的Environment.getCommandLineArgs()处理命令行参数。 主程序如下所示:

[STAThread]
static void Main()
{
        MainProcessor StartProgram = new MainProcessor();
        StartProgram.main();
        StartProgram = null;
}

和命令行参数的处理方式如下:

public void main() {
        String [] args = Environment.getCommandLineArgs();
        // process arguments
}

有没有办法从测试方法操纵命令行参数并使用如上所述的Environment.getCommandLineArgs()处理它们?

注意 :这是设计不当 MainProcessor (或其main方法)应采用(例如,通过构造函数)从Main参数传递的参数。

但是,如果您能够切换到2013版,则可以在Visual Studio中使用Fakes

  1. 在您的单元测试项目中,从References中 ,右键单击System然后选择Add Fakes Assembly。
  2. 在将要创建的新文件mscorlib.fakes中,添加Fakes部分:

     <ShimGeneration> <Add FullName="System.Environment"/> </ShimGeneration> 
  3. 重建

  4. 在测试中,可以对Environment静态方法调用进行存根:

     [TestMethod] public void TestSomeMethod() { using (ShimsContext.Create()) { ShimEnvironment.GetCommandLineArgs = () => new string[] { "arg1", "arg2" }; // Your test here. } } 

您也可以查看这篇文章

关于Visual Studio 2010,您可以使用名为Moles的Fakes前身,它与上面的非常相似。 只需从Extension Manager中添加Visual Studio 2010 Moles 我相信Moles将会是:

[TestMethod]
public void TestSomeMethod()
{
    using (MolesContext.Create())
    {
        Moles.MEnvironment.GetCommandLineArgs = () => new string[] { "arg1", "arg2" };

        // Your test here.
     }
}

与其从环境中提取命令行参数,不如仅将它们作为Main的参数?

    static void Main(string[] args)
    {
    }

现在,也将这些参数传递到MainProcessor的构造函数中。

    static void Main(string[] args)
    {
        var processor = new MainProcessor(args);
        processor.main();
    }

如果这是您Main方法所做的全部,那么您可以将测试重点放在MainProcessor上。 您也可以只调用Program.Main,传递您想要的任何内容,但是由于您唯一可以观察到的是是否抛出异常,因此它作为测试不是很有用。

如果出于某种原因,“ args”的标准处理方式神秘地停止工作,那么您将面临更大的问题……我们都可以。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM