How to Test Function Arguments #2423
-
I hope someone can help me. I want to know how to test for invalid parameters supplied to a function. For example, consider the following function:
The following code details a valid Pester test:
I want to create a Pester test to make sure that any changes to my function doesn't allow strings to be supplied, for example...
How can I create a Pester test for this? I cannot work out how to do it. Please help! Many thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hi. You may use the E.g. Describe 'Add-Ten' {
Context "Add-Ten: Testing invalid input" {
It 'Throws when passing non-int value to -Number' {
# Only check for exception
{ Add-Ten -Number "string" } | Should -Throw
# Verify specific error message (depends on OS-language)
{ Add-Ten -Number "string" } | Should -Throw -ExpectedMessage '*Cannot convert value "string" to type "System.Int32"*'
# Verify using error id (found using $error[0].FullyQualifiedErrorId)
{ Add-Ten -Number "string" } | Should -Throw -ErrorId "ParameterArgumentTransformationError,Add-Ten"
# Overkill mode. Verify details in the exception :)
$err = { Add-Ten -Number "string" } | Should -Throw -ErrorId "ParameterArgumentTransformationError,Add-Ten" -PassThru
# Check that the expected parameter failed
$err.Exception.ParameterName | Should -Be 'Number'
$err.Exception.ParameterType | Should -Be ([int])
# Verify the provided parameter value type
$err.Exception.TypeSpecified | Should -Be ([string])
}
}
} In this simple example you could just check the parameter type, e.g. |
Beta Was this translation helpful? Give feedback.
Hi. You may use the
Should -Throw
assertion for this by examining the error/exception.See https://pester.dev/docs/assertions/#throw and https://pester.dev/docs/commands/Should#throw
E.g.