Pester Test Throw

Welcome Forums Pester Pester Test Throw

This topic contains 3 replies, has 3 voices, and was last updated by

1 year, 5 months ago.

  • Author
  • #77955

    Points: 45
    Rank: Member


    I am trying to write a pester test for when my function throws an exception and I am unable to get this to work. I modified this some from my original code but the idea is the same. When I run Pester it fails at this assertion with an exception and says the test failed.

    I expect and receive the following exception.
    Exception Details: "MethodInvocationException: Exception calling "Substring" with 2 arguments: Index and length must refer to a location within the string.

    Please advise.

    function Select-SubString {
            [Parameter(Mandatory = $true,
                ValueFromPipeline = $true)]
        Write-Verbose "Taking input and creating substring variable"
        $substring = $($input.Substring(0, 25))
        return $substring
    Import-Module MyModule
    Describe "myModule.psm1" {
        InModuleScope myModule {
          $string = "abc"
          it 'should throw exception' {
           { $string.toString() | Select-SubString } | Should Throw MethodInvocationException
  • #77959

    Points: 22
    Rank: Member

    Instead of MethodInvocationException, use a piece of the exception message like "Exception calling "Substring"" The string you're asserting is actually the type of exception. Pester is looking at the message.

  • #77976

    Points: 45
    Rank: Member

    Thanks for the details Adam. That did work!

  • #84035

    Points: -19
    Rank: Member

    I wrote a set of assertions that handle this correctly. Here they are used in their own tests Assert-Throw

The topic ‘Pester Test Throw’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort