Is there any reason why using [Parameter()] on It block parameters in parameterised tests, breaks the tests? #2043
-
Taking the test suite as documented in the Pester readme: Describe 'Pester readme tests' -Tag 'Current' {
BeforeAll {
# your function
function Get-Planet ([string]$Name = '*') {
$planets = @(
@{ Name = 'Mercury' }
@{ Name = 'Venus' }
@{ Name = 'Earth' }
@{ Name = 'Mars' }
@{ Name = 'Jupiter' }
@{ Name = 'Saturn' }
@{ Name = 'Uranus' }
@{ Name = 'Neptune' }
) | foreach { [PSCustomObject]$_ }
$planets | where { $_.Name -like $Name }
}
}
# Pester tests
Describe 'Get-Planet' {
It "Given no parameters, it lists all 8 planets" {
$allPlanets = Get-Planet
$allPlanets.Count | Should -Be 8
}
Context "Filtering by Name" {
It "Given valid -Name '<Filter>', it returns '<Expected>'" -TestCases @(
@{ Filter = 'Earth'; Expected = 'Earth' }
@{ Filter = 'ne*' ; Expected = 'Neptune' }
@{ Filter = 'ur*' ; Expected = 'Uranus' }
@{ Filter = 'm*' ; Expected = 'Mercury', 'Mars' }
) {
param (
[Parameter()]
$Filter,
[Parameter()]
$Expected
)
$planets = Get-Planet -Name $Filter
$planets.Name | Should -Be $Expected
}
It "Given invalid parameter -Name 'Alpha Centauri', it returns `$null" {
$planets = Get-Planet -Name 'Alpha Centauri'
$planets | Should -Be $null
}
}
}
} In this example above, all I have done is to use the [Parameter()] attribute on the parameters passed into the It block, but for some strange reason, it breaks the tests with these parameter binding errors:
I discovered this whilst writing some of my own parameterised tests that were in-explicably failing and decided to reproduce this error on other code, to rule out anything I may have been doing wrong accidentally. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
It's because the use of ParameterAttribute will make the scriptblock advanced (like I'm not really sure why the param-block is in the README-example tbh. You don't really need it for normal usage. All the testcase parameters are made available both as named variables and the current testcase-object/dictionary itself can be accessed through Any reason you need the ParameterAttributes? If not I'd remove them or maybe even the whole param-block. |
Beta Was this translation helpful? Give feedback.
It's because the use of ParameterAttribute will make the scriptblock advanced (like
[CmdLetBinding()]
) which doesn't allow arguments by default. So it fails to bind some of the hard-coded values Pester passes to theIt
-scriptblock, in this case the object for the current testcase.I'm not really sure why the param-block is in the README-example tbh. You don't really need it for normal usage. All the testcase parameters are made available both as named variables and the current testcase-object/dictionary itself can be accessed through
$_
.Any reason you need the ParameterAttributes? If not I'd remove them or maybe even the whole param-block.