5

I would like to mock the System.Diagnostics.Process.Start call, so I've added a Fakes Assembly for the System Assembly.

The problem is that Start is a static method on System.Diagnostics.Process so I'm not getting a shim to be able to hook a delegate for the Start method.

What is the correct way of doing this?

InteXX
  • 6,135
  • 6
  • 43
  • 80

2 Answers2

11

So first of all you need to generate the Shim for the Process class.

After you create the Fakes for System you should see a folder called 'Fakes'. Inside that folder you need to edit the System.fakes file so that it will generate the Shims for System.Diagnostics.Process:

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true">
  <Assembly Name="System" Version="4.0.0.0"/>
  <ShimGeneration>
    <Add FullName="System.Diagnostics.Process"/>
  </ShimGeneration>
</Fakes>

After compiling you will be able to see in Object Explorer that Fakes Shims for Process have been genereated.

To use the Shim in a test you need to configure the Fake Process.Start delegate. A test might end up looking something like this:

using (ShimsContext.Create())
{
    System.Diagnostics.Fakes.ShimProcess.StartString = s =>
    {
        Console.WriteLine(s);
        return new StubProcess();
    };

    // A call to your method under test that exectues Process.Start rather than calling it directly
    var process = Process.Start("SomeString");
    Assert.IsTrue(process is StubProcess);
}

Obviously you might want to include something more relevant to your scenario test in your delegate and assertions.

See MSDN link

Martin
  • 1,057
  • 1
  • 9
  • 16
-1

You can use anonymous delegate

()=> Process.Start("your.exe");

For example

class Program
{
        static void Main(string[] args)
        {
            RunnerClass runner = new RunnerClass();

            runner.runProgram += (exeFile) => Process.Start("your.exe");
            string runApp = "run.exe";
            runner.runProgram(runApp);
        }
}
public class RunnerClass
{
   public Action<string> runProgram;
}    
progpow
  • 1,560
  • 13
  • 26
  • Sorry not get your response. Fakes are for Unit Testing so i don't see how i can mock the Process.Start method using your recommendation. – Klaus Stefan Gerber Sep 04 '13 at 11:18
  • Maybe for testing you try wrap Process.Start at method? – progpow Sep 04 '13 at 11:47
  • 1
    I think you understood my question wrong. I would like to use the Fakes Assembly Framework from Microsoft for this job and i have a problem using it for the Process.Start method. Of course there are other ways of mocking this functionality. – Klaus Stefan Gerber Sep 04 '13 at 12:25