diff --git a/tst/functions/Add-ShouldOperator.ts.ps1 b/tst/functions/Add-ShouldOperator.ts.ps1 index 3fb327bf2..71c4143c9 100644 --- a/tst/functions/Add-ShouldOperator.ts.ps1 +++ b/tst/functions/Add-ShouldOperator.ts.ps1 @@ -70,6 +70,78 @@ i -PassThru:$PassThru { } } + b 'Executing custom Should assertions' { + # Testing paramter and output syntax described in docs (https://pester.dev/docs/assertions/custom-assertions) + Get-Module Pester | Remove-Module + Import-Module "$PSScriptRoot\..\..\bin\Pester.psd1" + + t 'Works for simple functions with expected output' { + function CustomSimple ([string] $ActualValue, [switch] $Negate) { + $succeeded = 'A' -eq $ActualValue + if ($Negate) { $succeeded = -not $succeeded } + + # Default failure message. Not used by Should unless succeeded is $false + $failureMessage = "Expected 'A', but got '$ActualValue'." + if (-not $succeeded -and $Negate) { + $failureMessage = "Expected anything but 'A', but got '$ActualValue'." + } + + return [pscustomobject]@{ + Succeeded = $succeeded + FailureMessage = $failureMessage + } + } + + Add-ShouldOperator -Name CustomSimple -Test $function:CustomSimple + 'A' | Should -CustomSimple + 'B' | Should -CustomSimple -Not + $e = { 'B' | Should -CustomSimple } | Verify-AssertionFailed + $e.Exception.Message | Should -Be "Expected 'A', but got 'B'." + } + + t 'Works for advanced function with expected output' { + function CustomAdvanced { + [CmdletBinding()] + # Requires all mandatory parameters below as $args is disabled by default in advanced functions + param( + [string] $ActualValue, + [switch] $Negate, + $CallerSessionState + ) + $succeeded = 'A' -eq $ActualValue + if ($Negate) { $succeeded = -not $succeeded } + + # Default failure message. Not used by Should unless succeeded is $false + $failureMessage = "Expected 'A', but got '$ActualValue'." + if (-not $succeeded -and $Negate) { + $failureMessage = "Expected anything but 'A', but got '$ActualValue'." + } + + return [pscustomobject]@{ + Succeeded = $succeeded + FailureMessage = $failureMessage + } + } + + Add-ShouldOperator -Name CustomAdvanced -Test $function:CustomAdvanced + 'A' | Should -CustomAdvanced + 'B' | Should -CustomAdvanced -Not + $e = { 'B' | Should -CustomAdvanced } | Verify-AssertionFailed + $e.Exception.Message | Should -Be "Expected 'A', but got 'B'." + } + + t 'Assertion exceptions are surfaced to user' { + function CustomException ([string] $ActualValue, [switch] $Negate) { + throw [System.InvalidOperationException]'something went wrong' + } + + Add-ShouldOperator -Name CustomException -Test $function:CustomException + $e = { 'A' | Should -CustomException } | Verify-Throw + $e.Exception | Verify-Type -Expected ([System.InvalidOperationException]) + $e.Exception.Message | Should -Be "something went wrong" + } + } + b 'HelpMessage for built-in Should operators' { Get-Module Pester | Remove-Module Import-Module "$PSScriptRoot\..\..\bin\Pester.psd1"