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:
- 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)
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; } } //... }
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.
精彩评论