trying to test a function in pester 5.3.1 (latest) and ps7.2.1
function Remove-GraphUser
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[object]$cloudUsers
)
process
{
foreach ($User in $cloudUsers)
{
Remove-MgUser -UserId $User.id
$user
}
}
}
What is the best way to mock the remove-mguser function and test the resulting array of user objects output by the function remove-graphuser
tried this: but it seems to skip mock defined in beforeall.
BeforeDiscovery {
$cloud = Import-Csv $PSScriptRoot\files\cloud.csv
$result = Remove-GraphUser -cloud $cloud -Verbose
}
Describe 'Remove-GraphUser' -tags 'two' {
BeforeAll {
Mock Remove-MgUser {}
}
It 'should be called twice' {
Assert-MockCalled -CommandName Remove-MgUser -Times 2 -Scope describe
}
It '<_.id> should be removed from the cloud group' -ForEach $result {
$_.id | Should -Not -Be $null
}
}
this does not work either(the foreach it block is skipped but assert-mock runs)
BeforeAll {
Mock Remove-MgUser {}
$cloud = Import-Csv $PSScriptRoot\files\umbrella1_cloud.csv
$result = remove-graphuser -cloud $cloud -Verbose
}
Want to be able to mock remove-mggraphuser
because i dont want to actually remove users just test the logic and also be able to iterate over the $result
variable using -Foreach.
the $result
variable contains pscustomobjects
with id
and displayname
properties. I am tsting the function with 2 such objects.
$cloudusers = @([pscustomobject]@{id=1;displayname="john"},
[pscustomobject]@{id=2;displayname="doe"})
Update: I think I need to change the way i am testing the data so closing this
-ForEach is processed during the Discovery-phase, while BeforeAll is processed later during the Run-phase so the solution is to use a foreach loop inside the it block.
BeforeDiscovery {
$cloud = Import-Csv $PSScriptRoot\files\cloud.csv
$result = Remove-GraphUser -cloud $cloud -Verbose
}
Describe 'Remove-GraphUser' -tags 'two' {
BeforeAll {
Mock Remove-MgUser {}
}
It 'should be called twice' {
Assert-MockCalled -CommandName Remove-MgUser -Times 2 -Scope describe
}
It user should be removed from the cloud group' -ForEach $result {
foreach ($index in $result)
{
$index.id | Should -Not -Be $null
$index.ad_id | Should -Be $null
}
}
}