Non-Terminating Error Unit test

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

 

 

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

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.