Tech Off Post

Single Post Permalink

View Thread: How to mimic cmd.exe parsing functionality for unit tests.
  • User profile image

    Command line processing is a bit more complex than this. Yes, CMD.EXE does some crafty processing that splits the command line into a string array. Unfortunately, so does PowerShell, but it does things differently. Their similar, but not the same. I think you have 3 options here.

    1. Use a command line parser that parses the full command line and not just the args the shell gives you. This ensures the syntax is the same regardless of the shell, which is both a good and a bad thing.
    2. Right unit tests that test the syntax of both shells, and hope we never get a mainstream third (or more) shell. This seems like the most difficult and brittle option.
    3. Write unit tests that test the args, not the command line. You can create your own helper method to make it easier to write. Simplest would be a function that takes a params string array and returns the array, but that just saves you a few keystrokes. More robust would be to just write a Parse method that parses the string, similar to what you're asking for, but that doesn't care what syntax is used. Pick a simple syntax to parse and ignore what the various shells do. Heck, in most cases a simple Split on the space character would be good enough. More robust, just borrow a CSV parser which would allow you to represent everything in a single string with little effort.

    I'd probably go for a CSV parser. Forget about worrying about the shell syntax, it's not really relevant if your command line parser is parsing an args array.