Search code examples
c#unit-testingseleniumnunitiis-express

Execute Command Line Statements from Within NUnit


I've got a unit test project where I'm using Selenium to automate UI tests. The intention is to eventually deploy this to a CI server. As part of this process, I'm trying to start the website programmatically in IIS Express.

So in the Setup method of the unit test class, I'd like to start the website in IIS Express from the command line, using the following code:

var console = new Process
                  {
                    StartInfo =
                    {
                      FileName = "cmd.exe",
                      RedirectStandardInput = true,
                      UseShellExecute = false
                    }
                  };
console.Start();
console.StandardInput.WriteLine("iisexpress /path:[my_path] /port:9090");

This code works, unless I'm trying to run it in the Setup fixture of an NUnit test. In that case, I can't get a new console window to open and execute code.


Solution

  • In general, using cmd.exe is problematic unless you're using the Windows Shell. Run iisexpress process directly as follows

    using (Process proc = new Process())
    {
        proc.StartInfo.FileName = "iisexpress.exe";
        proc.StartInfo.Arguments = " /path:[my_path] /port:9090";
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.Start();
        proc.WaitForExit();
        //output from the process run
        Console.Out.WriteLine(proc.StandardOutput.ReadToEnd());
    }
    

    If you need to use the shell,then cmd.exe expects a /C switch to execute a process passed as an argument, as below:

        proc.StartInfo.FileName = "cmd.exe";
        proc.StartInfo.Arguments = "/C iisexpress /path:[my_path] /port:9090";