2

我写了一个纠缠测试来检查某些文件夹和文件是否存在。纠缠测试效果很好,但如果使用 -Verbose 选项调用测试,我想包括修复建议。但我似乎无法将 -Verbose 参数用于实际测试。

文件夹/文件结构:

Custom-PowerShellModule
    |   Custom-PowerShellModule.psd1
    |   Custom-PowerShellModule.psm1
    \---Tests
            Module.Tests.ps1

以下只是纠缠测试的顶部:

$Here = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"

Describe "Module Minimum Requirements Tests.  Use -Verbose for Suggested Fixes" -Tags Module {
  Context "Test:  Verify File Counts = 1" {
    Write-Verbose  "If you receive an error, verify there is only 'ONE' PSD1 File and only 'ONE' PSM1 File."
    It "There is only one PSD1 file" { (Get-ChildItem "$Here\..\" *.psd1).count | Should be 1 }
    It "There is only one PSM1 file" { (Get-ChildItem "$Here\..\" *.psm1).count | Should be 1 }
  }
}
4

3 回答 3

2

Per the other answer, it doesn't seem to be possible to use Write-Verbose when running the script with the Invoke-Pester command. I think this may be because using the Invoke-Pester command means that you script is interpreted rather than directly executed by the PowerShell engine. The next best alternative would be to add in If statements that perform the same checks as your tests and then use Write-Host or Write-Warning to give instructions if they are negative. I have done that occasionally in the past.

You can however use -verbose if you are executing the script directly (e.g just directly running the *.tests.ps1 file). However to do so you need to add [cmdletbinding()] and a Param block to the top of your script:

[cmdletbinding()]
Param()

$Here = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"

Describe "Module Minimum Requirements Tests.  Use -Verbose for Suggested Fixes" -Tags Module {
  Context "Test:  Verify File Counts = 1" {

    Write-Verbose  "If you receive an error, verify there is only 'ONE' PSD1 File and only 'ONE' PSM1 File."

    It "There is only one PSD1 file" { (Get-ChildItem "$Here\..\" *.psd1).count | Should be 1 }
    It "There is only one PSM1 file" { (Get-ChildItem "$Here\..\" *.psm1).count | Should be 1 }
  }
}
于 2017-04-18T17:05:47.130 回答
1

cmdlet的-Verbose开关Invoke-Pester在测试用例中不可用。您必须显式传递此参数才能访问测试用例。

这是基于您的脚本的示例:

Param([Bool]$Verbose)

Describe "Module Minimum Requirements Tests.  Use -Verbose for Suggested Fixes" -Tags Module {
    Context "Test:  Verify File Counts = 1" {
    Write-Verbose  "If you receive an error, verify there is only 'ONE' PSD1 File and only 'ONE' PSM1 File." -Verbose:$Verbose
    It "There is only one PSD1 file" { (Get-ChildItem "$Here\..\" *.psd1).count | Should be 1 }
    It "There is only one PSM1 file" { (Get-ChildItem "$Here\..\" *.psm1).count | Should be 1 }
   }
}

Invoke-Pester -Script @{Path='path' ; Parameters = @{ Verbose = $True }}
于 2017-04-14T05:36:41.013 回答
1

除了将 Verbose 标志显式传递给测试用例外,您还可以在范围内更改 VerbosePreference 的默认值:

$VerbosePreference = $Env:MyVerbosePreference

然后你可以从外部控制它:

$Env:MyVerbosePreference= 'Continue'
Invoke-Pester ...
于 2020-04-07T21:50:22.863 回答