开发者

How can i pass command line arguments when running unit test in visual studio 2008 IDE?

开发者 https://www.devze.com 2023-03-18 17:07 出处:网络
Is there a way to pass command line arguments to the application cotext during unit testing in Visual Studio 2008? Part of my code needs to be configured this way and i can only do this by passing arg

Is there a way to pass command line arguments to the application cotext during unit testing in Visual Studio 2008? Part of my code needs to be configured this way and i can only do this by passing arguments.

I've checked in the de开发者_如何转开发bug mode and command line arguments has been filled with some test related data.

Thanks!


Ok,

I was digging for a long time and was not able to find any way to pass CLI arguments directly.

However there is pretty nice workaround:

  1. You need a class which is parser and holder for CLI agruments. In my case it is astatic class with static properties. Of course it was returning null values during unit testing (no recognized CLI arguments)
  2. Your CLIArgsHolder class must be written in a sane way to return nulls and NOT throw exceptions when it initializes if any of CLI args is missing. In my case I parse only when private field is null or empty using static property's get.

    public static class MyCLIArgsHandler
    {
         private string mAppName = null;
         private string mStationName = null;
    
         public string StationName
         {
             get
             {
                 if(string.isNullOrEmpty(MyCLIArgsHandler.mStationName))
                 {
                    //PARSE CLI ARGS
                 }
                 return MyCLIArgsHandler.mStationName;
             }
         }
         //...
    }
    
  3. Before you start actuall testing you can inject sample values to fields of that class so when:

    [ClassInitialize()]
    
    public static void MyClassInitialize(TestContext testContext)
    {            
        PrivateType type = new PrivateType(typeof (MyCLIArgsHolder));
        type.SetStaticFieldOrProperty("mAppName", "myTestAppName");
        type.SetStaticFieldOrProperty("mStationName", "myTestStationName");
    }
    

Voila!

Now all your classes can use your MyCLIArgsHolder with values you put in your test class initialization.

0

精彩评论

暂无评论...
验证码 换一张
取 消