【发布时间】:2018-03-08 19:58:40
【问题描述】:
当我运行以下纠缠测试时,我希望它能够捕获预期的错误,但它没有。但是当我使用不同的函数和不同的 throw 语句运行测试时,它可以工作。
Pester 测试:
Describe "Remove-GenericCredential Function Tests" {
$InternetOrNetworkAddress = 'https://PesterTestUser@PesterTestURl.com'
Context "Test: Remove-GenericCredential -InternetOrNetworkAddress '$InternetOrNetworkAddress' (Credential does not exist)" {
It "This Command threw an error. The credential does not exist." { { (Remove-GenericCredential -InternetOrNetworkAddress $InternetOrNetworkAddress -Confirm:$false) } | should throw "Remove-GenericCredential : Credential $InternetOrNetworkAddress not found" }
}
}
未被捕获的错误:
Remove-GenericCredential : Credential https://PesterTestUser@PesterTestURl.com not found
At C:\Users\klocke7\Documents\WindowsPowerShell\Modules\Ford_CredentialManager\Tests\Remove-GenericCredential.Tests.ps1:30 char:76
+ ... xist." { { (Remove-GenericCredential -InternetOrNetworkAddress $Inter ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Remove-GenericCredential
[-] This Command threw an error. The credential does not exist. 44ms
Expected: the expression to throw an exception with message {Remove-GenericCredential : Credential https://PesterTestUser@PesterTestURl.com not found}, an exception was not raised, message was {}
from C:\Users\klocke7\Documents\WindowsPowerShell\Modules\Ford_CredentialManager\Tests\New-GitHubCredential.Tests.ps1:59 char:176
+ ... e $UserName -Token 'NotAGitHubTokenSpecialCharacters!@#$%^&*') } | sh ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
at <ScriptBlock>, C:\Users\klocke7\Documents\WindowsPowerShell\Modules\Ford_CredentialManager\Tests\Remove-GenericCredential.Tests.ps1: line 30
30: It "This Command threw an error. The credential does not exist." { { (Remove-GenericCredential -InternetOrNetworkAddress $InternetOrNetworkAddress -Confirm:$false) } | should throw 'Remove-GenericCredential : Credential https://PesterTestUser@PesterTestURl.com not found' }
【问题讨论】:
-
你能告诉我们
Remove-GenericCredential或者至少是引发原始错误的代码吗? -
写入错误-消息“未找到凭据 $InternetOrNetworkAddress”-Category ObjectNotFound
-
不应该是
.... | Should -Throw而不是.... | Should Throw吗?并且, throw 后面应该跟在 throw 语句中使用的字符串,例如 { throw "mud" } |应该 - 扔“泥”会过去。否则,请仔细检查您认为该函数在做什么,它在做什么。 -
Should Throw 和 Should -Throw 产生相同的错误。我的抛出字符串似乎与 write-error 语句抛出的字符串相同。
标签: powershell pester