Saturday, February 7, 2015

FluentShellUnit - Create a dummy object


In the previous entry of this series of FluentShellUnit, we saw how to use the framework to invoke a method on a PowerShell module and perform assertions. This article we’ll see how we can pass in parameters to a method and use a simple stub/ dummy object for a PowerShell cmdlet to isolate our code under test.
FluentShellUnit’s execute method’s overload takes a Dictionary as argument that is used to pass the parameters to the calling method. For e.g. The below method, passes the value “VSTest” to the parameter “context” for the Get-WelcomeMessage function in the TestModule

var actual = PsFactory.Create(HostState.Core)
                .Load(@"TestModule\Modules\TestModule.psm1")
                .Execute
                (
                    "Get-WelcomeMessage",
                    new Dictionary<string, string>
                    {
                        {"context", "VSTest"}
                    }
                )
                .FirstResultItemAs<string>();
Assert.IsTrue(actual.Contains("VSTest"));
                    
Function Get-WelcomeMessage{
      param([string] $context)
     
      "Welcome from context {0}" -f $context
}

FluentShellUnit also allows you to create a simple Dummy object (http://xunitpatterns.com/Mocks,%20Fakes,%20Stubs%20and%20Dummies.html) , that has no implementation and does not do anything when invoked. The below example shows how to create a Dummy for the Write-Host cmdlet when invoked from a method.


var actual = PsFactory.Create(HostState.Core)
                .Load(@"TestModule\Modules\TestModule.psm1")
                .Stub("Write-Host")
                .Execute
                (
                    "Get-WelcomeMessage",
                    new Dictionary<string, string>
                    {
                        {"context", "VSTest"}
                    }
                )           
                .FirstResultItemAs<string>();
Assert.IsTrue(actual.Contains("VSTest"));

Where the Get-WelcomeMessage implementation is as

Function Get-WelcomeMessage{
      param([string] $context)
      $message = "Welcome from context {0}" -f $context
      Write-Host "Setting the welcome message as {0}" -f $message
      $message
}

No comments: