Sunday, January 18, 2015

Creating your own unit testing framework for PowerShell - part 4

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);
    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

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: