使用 Pester 测试强制参数 [英] Testing for mandatory parameters with Pester
问题描述
我想弄清楚如何对丢失的参数进行 Pester 测试:
I'm trying to figure out how to have Pester test for parameters that are missing:
Find-Waldo.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
Describe 'Mandatory paramters' {
it 'ComputerName' {
{
$Params = @{
#ComputerName = 'MyPc'
ScriptName = 'Test'
}
. "$here\$sut" @Params
} | Should throw
}
}
Find-Waldo.ps1
Param (
[Parameter(Mandatory)]
[String]$ComputerName,
[String]$ScriptName
)
Function Find-Waldo {
[CmdletBinding()]
Param (
[String]$FilePath
)
'Do something'
}
每次我尝试 assert
结果或简单地运行测试时,它都会提示我输入 ComputerName
参数而不是测试失败.
Every time I try to assert
the result or simply run the test, it will prompt me for the ComputerName
parameter instead of failing the test.
我在这里遗漏了一些非常明显的东西吗?有没有办法测试强制参数的存在?
Am I missing something super obvious here? Is there a way to test for the presence of mandatory parameters?
推荐答案
根据 Mathias 的评论,您无法真正测试是否缺少 Mandatory 参数,因为 PowerShell 会提示输入而不是抛出错误.根据 他从 Pester 团队链接的评论,您可以使用 Get-Command
测试脚本中的 Mandatory 参数设置(假设它是为该变量设置的唯一参数属性)
Per the comments from Mathias, you can't really test for whether a Mandatory parameter is missing because PowerShell prompts for it rather than throwing an error. Per the comment he linked to from the Pester team you could use Get-Command
to test for the Mandatory parameter setting in the script (assuming it is the only parameter attribute set for that variable)
((Get-Command "$here\$sut").Parameters['ComputerName'].Attributes.Mandatory | Should Be $true
另一种选择是在这种情况下不使用强制参数,而是使用一个执行 Throw
作为参数默认值的脚本块:
An alternative option would be to not use Mandatory parameters in this instance, and instead have a script block that does a Throw
as the default value of the parameter:
Param (
[String]$ComputerName = $(Throw '-ComputerName is required'),
[String]$ScriptName
)
如果脚本始终用作自动化流程的一部分(而不是通过用户执行),这可能是首选,因为它允许您控制/捕获其行为并避免它在执行过程中卡住.然后,您可以按照最初建议的方式测试脚本:
If the script is always used as part of an automated process (instead of via user execution) this might be preferred as it allows you to control/capture its behavior and avoids it getting stuck during execution. You can then test the script as you had originally proposed:
Describe 'Mandatory paramters' {
it 'ComputerName' {
{
$Params = @{
#ComputerName = 'MyPc'
ScriptName = 'Test'
}
. "$here\$sut" @Params
} | Should throw '-ComputerName is required'
}
}
这篇关于使用 Pester 测试强制参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!