How can I test parameter validation in Pester?

800 views
Skip to first unread message

Dave Neeley

unread,
Apr 11, 2013, 11:34:54 AM4/11/13
to pes...@googlegroups.com
Let's say I have the following methods

function Replace-BuildTemplate {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelinebyPropertyName=$true)]
        $buildTypes,
        [ValidateScript({Validate-BuildTemplateLocator $_})]
        $template
    )
    process {
         snip...
    }
}

function Validate-BuildTemplateLocator {
    param (
        $template
    )
    process {
        $template -match "id:\(template:btTemplate\d+\)"
    }
}


And a test

Describe "Replace Build Template with New Template" {
    Context "Validate Template Locator" {
        It "Fails validation when an incomplete template locator is passed in" {
            Mock write-error -MockWith {return $msg -match "Cannot validate argument on parameter 'template'"} -verifiable
            $mockBuildTypes | Replace-BuildTemplate -template "gobbledygook"
            Assert-VerifiableMocks
        }
    }
}


The result produced is:

Describing Replace Build Template with New Template
  Validate Template Locator
[-]  1ms
     Cannot validate argument on parameter 'template'. The "Validate-BuildTemplateLocator $_" validation script for the argument with value "gobbledygook" did not return
true. Determine why the validation script failed and then try the command again.
     at line: 173 in ...



I'm sure at some point powershell is calling write-error to present the validation failure message, but I can't get to it from my test.

Scott Muc

unread,
Apr 11, 2013, 3:58:52 PM4/11/13
to pes...@googlegroups.com
Interesting problem! I've found testing the output streams quite hard. Here's my take on testing your code:


The mock is used to test the interaction between the function that uses the validator. For this I don't really care about what gets passed to it, I just want to know that I use it. Then I unit test the validating function separately.This is unit testing at a pretty granular fashion.

Now, that style bypasses your question a bit. Yes, I think Pester should have some ability to know what gets written to standard out and standard error. I just don't know how to do that yet :-). However, I think the test strategy above can at least help you move forward.

Thank you for using Pester :-)

Scott
Reply all
Reply to author
Forward
0 new messages