Before we proceed into how we can stub out commands in our
test framework, we’ll see how the AddScript method works and how to use it to
execute a script block in powershell. The AddScript method adds a script to the
end of the pipeline of the PowerShell object and can be invoked by the Invoke
method. We’ll use this method to add our dummy function as a script object to
the pipeline so that when this command is called later from a function, it’s
going to call the dummy function that was added using the AddScript method.
So our Stub() is implemented as.
public PowerShellHost Stub( string method)
{
if (_runspace == null)
{
throw new ArgumentException("The PowerShell host should be setup before invoking
the methods");
}
var script = String.Format("Function
{0}
{{}}", method);
_shell.AddScript(script).Invoke();
return this;
}
You can also see that I’ve used the return value of the
method as the PowerShellHost, so that I can use a fluent interface model for my
test methods. A sample test method using Stub to the Write-Host command can be
written as
var psHost = new PowerShellHost<XModule>();
var actual = psHost
.Stub("Write-Host")
.Execute("Get-Greetings");
var result = actual.GetGreetings.Result.Select(psObject =>
psObject.BaseObject).OfType<string>().First();
Assert.AreEqual<string>(result, "Hello from VSTest");
Next we’ll see how exception handling can be taken care.
No comments:
Post a Comment