这个 Pester 测试:
BeforeAll {
function Get-HtmlFileDetail {
param (
[string[]]$Path = 'E:\Domains',
[string[]]$Include = 'Alive*.html'
)
return Get-ChildItem -Path $Path -Include $Include -File -Recurse | ForEach-Object {
[PSCustomObject]@{
Drive = Split-Path -Path $PSItem.FullName -Qualifier
Parent = Split-Path (Split-Path $PSItem.FullName -Parent) -Leaf
FileName = Split-Path -Path $PSItem.FullName -Leaf
BodyText = (Get-Content -Path $PSItem.FullName -Raw | Select-String -Pattern '(?<=<body>).*?(?=</body>)').Matches.Value
}
}
}
}
Describe 'FileSytem' {
Context 'Get-HtmlFileDetail' {
Context 'when path and include are NOT specified' {
BeforeAll {
Mock -CommandName Get-ChildItem -MockWith { }
}
It 'should use defaults' {
Get-HtmlFileDetail | Should -Invoke -CommandName Get-ChildItem -Times 1 -ParameterFilter {
$Path -eq 'E:\Domains' -and $Include -eq 'Alive*.html'
}
}
}
}
}
错误:
[-] FileSytem.Get-HtmlFileDetail。当未指定路径和包含时。应使用默认值 620ms (513ms|107ms) ParameterBindingException:找不到与参数名称“文件”匹配的参数。
我认为 Pester 试图绑定
Get-ChildItem
的参数,尽管它会被嘲笑。由于路径不存在,无法绑定动态参数-File
,所以会抛出ParameterBindingException
,测试失败。
Should -HaveParameter
而不是模拟来断言参数具有正确的默认值:
BeforeAll {
function Get-HtmlFileDetail {
param (
[string[]]$Path = 'E:\Domains',
[string[]]$Include = 'Alive*.html'
)
return Get-ChildItem -Path $Path -Include $Include -File -Recurse | ForEach-Object {
[PSCustomObject]@{
Drive = Split-Path -Path $PSItem.FullName -Qualifier
Parent = Split-Path (Split-Path $PSItem.FullName -Parent) -Leaf
FileName = Split-Path -Path $PSItem.FullName -Leaf
BodyText = (Get-Content -Path $PSItem.FullName -Raw | Select-String -Pattern '(?<=<body>).*?(?=</body>)').Matches.Value
}
}
}
}
Describe 'FileSytem' {
Context 'Get-HtmlFileDetail' {
Context 'when path and include are NOT specified' {
It 'should use defaults' {
Get-Command Get-HtmlFileDetail | Should -HaveParameter -ParameterName Path -DefaultValue 'E:\Domains'
Get-Command Get-HtmlFileDetail | Should -HaveParameter -ParameterName Include -DefaultValue 'Alive*.html'
}
}
}
}