Non-Terminating Error Unit test

Welcome Forums Pester Non-Terminating Error Unit test

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

 
Senior Moderator
2 months, 3 weeks ago.

  • Author
    Posts
  • #167821

    Participant
    Topics: 1
    Replies: 2
    Points: 46
    Rank: Member

    Hello all,

    I'm pretty new to the unit testing world and have been working through the Pester Book.  I'm struggling with mocking Set-ADUser when it has a non-terminating error.

    Generally, I want to set a property with Set-ADUser and pipeline an object with what happened (success or failure for any reason)  My pipeline object does contain more information than this sample.

    Rough code in function:

    Try{
      Set-ADuser $Props
      
      $UpdateProps = @{
        sammaccountname = $user.samaccountname
        status = 'updated'
      }
    
      $OutObject = New-Object PSObject -property $UpdateProps
      $OutObject
    }
    Catch{
      $FailedProps = @{
        samaccountname = $User.samaccountname
        status = 'failed'
      }
      
      $OutObject = New-Object PSObject -Property $FailedProps
      $OutObject
    }
    
    

    How can I mock Set-ADUser to hit the catch block?  I know the code hits the catch block if i test my function with bad input.   I've looked at some references to $ErrorAction and counting non terminating errors, but I can't ever get the mock right that it hits the catch.

    Thanks in advance.

    Dan

     

     

  • #167827

    Participant
    Topics: 1
    Replies: 2
    Points: 46
    Rank: Member

    I worked out a solution.

    Set-AdUser was set with -ErrorAction 'Stop'

    The Mock

    Mock -CommandName Set-ADUser -MockWith { Write-Error 'Some annoying error occurred' }

     

    The test

    $Result = Set-CustomAttribute 
    $Result.Status | Should -Be 'failed'

     

    If there is a better or the more correct way,  I'm be keen to learn it.

     

    Dan

  • #167863

    Senior Moderator
    Topics: 8
    Replies: 1085
    Points: 3,650
    Helping Hand
    Rank: Community Hero

    Error handling in a script is always important and -ErrorAction is a builtin option in all PowerShell cmdlets. Catch block is consumed only in case of a terminating error. for a cmdlet which throws a non terminating error, it just throws and continues to the nest statement, this is controlled using the -ErrorAction for that cmdlet.
    By setting its value to Stop makes it to terminate, hence the catch block is consumed.

You must be logged in to reply to this topic.