Sunday, February 22, 2015

Create stub objects as arguments for system under test

Sometimes you need to pass a stub object as an argument to a function or script that is under test. FluentShellUnit API exposes extension methods to add methods and properties on the PSObject so that the object can have the desired behavior when used in the system under test.
Function Get-VirtualDirectoryForWebApp
{
       param
       (
              $WebApplication,
              [String] $Zone
       )
       $path = $Webapplication.GetIisSettingsWithFallback($Zone).Path
       $path
}

The Get-VirtualDirectoryForWebApp returns the location of the virtual directory for a SharePoint webapplication by using the IisSettings object for a Zone. If you want to test this method, you need to stub a SharePoint WebApplication and then pass it to the method.
As mentioned before, the first step is to create a PSObject and then add the required methods and properties to the object.

var webApplication = new PSObject();
var iisSettings = new PSObject();
var path = @"C:\MyWeb\wss\mywebapp";
iisSettings.StubProperty("Path", path);
webApplication.StubMethod("GetIisSettingsWithFallback", objects => objects[0].ToString() == "Default" ? iisSettings : null);

The StubMethod accepts a PsDelegate implementation that accepts a param object[] and returns an object.
public delegate object PsDelegate(params object[] argsObjects);


Now you can use this stub object as an argument to the Get-VirtualDirectoryForWebApp method and get the desired output.

var actual = PsFactory.Create(HostState.Core)
    .FailOnNonTerminatingError()
    .Load(@"TestModule\Modules\TestModule.psm1")
    .Execute
    (
        "Get-VirtualDirectoryForWebApp",
        new Dictionary<string, object>
        {
            {"WebApplication", webApplication},
            {"Zone", "Default"}
        }
    )
    .FirstResultItemAs<string>();

Assert.IsTrue(actual == path);

You can download the latest version from github or the package from Nuget.

No comments: