Trujllo
Trujllo

Reputation: 110

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
  }
}

Upvotes: 4

Views: 3377

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200443

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.

Upvotes: 3

Related Questions