Search code examples
unit-testingpowershellpester

Unit test ParameterBindingValidationException


Can somebody show me the best way to test non-nullable string parameters with Pester?

I receive a ParameterBindingValidationException when I pass an empty string my PowerShell module.

function Get-MyFunc {
  param (
    [parameter(Mandatory=$true)]
    [string]$stringParameter
  )

  ## rest of function logic here
}

I was expecting to be able to do this in my test:

Describe 'When calling Get-MyFunc with empty parameters' {
  It 'Should throw an exception' {
    Get-MyFunc '' | Should Throw
  }
}

Or this:

Describe 'When calling Get-MyFunc with empty parameters' {
  It 'Should throw an exception' {
    PesterThrow { Get-MyFunc '' } | Should Be $true
  }
}

Solution

  • Put the check in a scriptblock:

    Describe 'When calling Get-MyFunc with empty parameters' {
      It 'Should throw an exception' {
        { Get-MyFunc '' } | Should Throw
      }
    }
    

    See Pester Wiki.