Saturday, February 7, 2015

FluentShellUnit - Create a stub from script block

A stub is a test-specific replacement for a real object that feeds the desired indirect inputs to the system under test. FluentShellUnit supports stubbing by using a scriptblock that is loaded from a script file if the input to be provided by the stub/ the return value is a complex type. If the return value for a stub is a simple string, then you don’t need to use a script block.
For e.g, the below given method in the module calls the Get-SPWebApplication cmdlet that returns a SharePoint web application while invoked in the execution process of the method Get-WebApplicationTest

Function Get-WebApplicationTest{
      param([string] $webAppName)
      $webApp = Get-SPWebApplication -Name $webAppName
      return $webApp
}
In a test execution context, you don’t want to invoke the Get-SPWebApplication cmdlet using the SharePoint API. To create a stub for the Get-SPWebApplication cmdlet, you can now create a script file that contains a method Get-SPWebApplication and use your custom implementation there.

Function Get-SPWebApplication{
      param([string]$Name)
      @{"Url" = "http://dummywebapplication.nl"; "Description" = "Description of the webapplication"}
}

I’ve created a scriptfile WebApplication.ps1 that contains this method.
While invoking the Get-WebApplicationTest method from the FluentShellUnit tests, you can now pass this scriptblock to use as a stub to the actual Get-SPWebApplication cmdlet like

var actual = PsFactory.Create(HostState.Core)
                .Load(@"TestModule\Modules\TestModule.psm1")
                .StubFromFile("WebApplication.ps1")
                .Execute
                (
                    "Get-WebApplicationTest",
                    new Dictionary<string, string>
                    {
                        {"webAppName", "MySPWebApplication"}
                    }
                )
                .FirstResultItemAs<Hashtable>();
Assert.IsTrue(actual.Contains("Url"));




No comments: