Command Line Arguments with Visual Studio Unit Tes

2019-06-19 17:24发布

问题:

I'm supposed to use the VS unit testing framework to ensure all code is working correctly. However I'm having A LOT of trouble getting tests that require command line arguments to work (since command line inputs must be given at runtime...and with unit tests there is no real "runtime"). Is there a way to run my unit tests with command line argument inputs? I realized this is not the ideal way to construct a program, but I unfortunately do not decide how the testing process works.

I've read that I can potentially write a batch file and include it in the MStest/testcontainer folder. There are some hurtles I have to clear in order to do it this way though. These hurtles include:

1) I know nothing about batch files

2) I don't know where the MStest/testcontainer folder is, how to access it, how it works, or even how to add files to it (since it seems to be hidden or not easily accessible).

3) I don't know what I would do with the batch file even if it was written correctly and in the MStest/testcontainer folder. How are my tests even supposed to know it's there, let alone take input from it?

So to summarize: How does one make VS unit tests take in command line arguments? If I DO have to use the batch file method, I would much appreciate it being explained to me like I'm 5. I apologize if I appear a little helpless in this subject, but I can't find any clear or useful explanations on how any of these things work within this specific context.

Thanks a ton.

回答1:

Short, will solve your problem, and incorrect approach to unit testing :-) :

If your program requires command line arguments, then it should have static void Main(string[] args) method.

Just write your unit tests to call this method with whatever command-line arguments you would normally add.

Longer, much better way: Split yout functionality in 2 - a class which does the work, and just a simple program, which gets the command line arguments and pass them to the worker.

The write 2 unit tests - one, that Main(xxx) actually passes the arguments to your class, and many unit tests for your actual worker to verify its behavior based on these arguments.



回答2:

You could start a new instance of your program within the test method with the Process class. Something like:

Process prop = new Process();
prop.StartInfo.FileName = "myProgram.exe";
prop.StartInfo.Arguments = "-arg1 -arg2";
prop.StartInfo.RedirectStandardOutput = true;
prop.StartInfo.RedirectStandardInput = true;
prop.Start();
// You can then use prop.StandardInput and prop.StandardOutput for testing.
prop.WaitForExit();
int code = prop.ExitCode;