Igor
Igor

Reputation: 609

Stub or Shim Process class with Microsoft Fakes

I have this code:

Have a method like this:

private void Invoke(string executablePathAndFile, string commandLineArguments)
{
    Process process = ProcessInstance;
    ProcessStartInfo startInfo = ProcessStartInfo;

    startInfo.FileName = executablePathAndFile;
    startInfo.Arguments = commandLineArguments; 

    process.StartInfo = startInfo;

    process.Start();

    if (WaitForExit)
        process.WaitForExit();
}

I am trying to stub or shim out Process class' method calls. Microsoft Fakes only creates a Stub and not a Shim (not sure why). I can provide StubProcess in a shimmed out call to ProcessInstanceGet:

InvokeExecutableAction sut = new InvokeExecutableAction(actionElement);
StubProcess stubProcess = new StubProcess();
ShimInvokeExecutableAction sutShim = new ShimInvokeExecutableAction(sut)
{
    ProcessInstanceGet = () => stubProcess
};

but when the code under test gets to process.Start() , it comes back with a Win32Exception. I am unable to provide an alternate implementation for the stub's Start method like:

Is there a way to achieve what I need (i.e. provide an alternate execution for Start() method) or refactor the code to be more testable (without going overboard!!!)?

Upvotes: 2

Views: 1429

Answers (3)

erhan355
erhan355

Reputation: 1086

You have to edit the System.fakes file as following, 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>

Possible Duplicate: How to use Microsoft Fakes Assemblies on Process.Start

Upvotes: 1

Jonathan
Jonathan

Reputation: 11

Add this in the XML of system.fakes and not in the XML of mscorlib.fakes

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

Upvotes: 1

Rahul
Rahul

Reputation: 77936

To my knowledge, you will have to first add a fakes assembly. process class present in System.dll and so

1.In Solution Explorer, expand your unit test project’s References.

2.Select the system.dll assembly.

3.On the shortcut menu, choose Add Fakes Assembly.

Then use the shim method instead. A good example can be found here https://msdn.microsoft.com/en-us/library/hh549176.aspx

[Test]
public void Y2kCheckerTest() {
  using(ShimsContext.Create()) {
    ShimDateTime.NowGet = () => new DateTime(2000, 1, 1);
    Y2KChecker.Check();
  }
}

Upvotes: 0

Related Questions