. $PSScriptRoot\..\..\Load-PesterModules.ps1 $here = Split-Path -Parent $MyInvocation.MyCommand.Path $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.tests\.', '.' $functionPath = Join-Path -Path $here -ChildPath $sut Write-Host "Overriding SUT: $functionPath" Import-Module $functionPath -Force $moduleForMock = "" Describe "Get-WindowsServiceApplicationName" { Mock -CommandName Write-Warning -MockWith {} -ModuleName $moduleForMock $fakeServiceName = -join ((65..90) + (97..122) | Get-Random -Count 15 | ForEach-Object {[char]$_}) Context "Error Handling" { It "Does not throw if the service is not found" { { Get-WindowsServiceApplicationName "$fakeServiceName" } | Should -Not -Throw Assert-MockCalled -CommandName Write-Warning -Times 1 -Exactly -Scope It ` -ModuleName $moduleForMock -ParameterFilter { $Message -match "Unable to find service detail" } } It "Does not throw if the service has no pathname property" { Mock -CommandName Get-CIMInstance -MockWith { return New-Object PSObject -Property @{ NoPathName="Here"; } } -ModuleName $moduleForMock { Get-WindowsServiceApplicationName "$fakeServiceName" } | Should -Not -Throw Assert-MockCalled -CommandName Get-CIMInstance -Times 1 -Exactly -Scope It -ModuleName $moduleForMock Assert-MockCalled -CommandName Write-Warning -Times 1 -Exactly -Scope It ` -ModuleName $moduleForMock -ParameterFilter { $Message -match "Unable to find the property PathName" } } It "Returns one service if more than one matching service is found" { Mock -CommandName Get-CIMInstance -MockWith { @( [PSCustomObject]@{ Name = "FakeService"; PathName = "NoWay"; }, [PSCustomObject]@{ Name = "FakeService2"; PathName = "NoHow"; } ) } -ModuleName $moduleForMock Get-WindowsServiceApplicationName "$fakeServiceName" | Should -HaveCount 1 Assert-MockCalled -CommandName Get-CIMInstance -Times 1 -Exactly -Scope It -ModuleName $moduleForMock Assert-MockCalled -CommandName Write-Warning -Times 1 -Exactly -Scope It ` -ModuleName $moduleForMock -ParameterFilter { $Message -match "More than one service found" } } } Context "Happy Path" { It "Returns only the PathName property" { Mock -CommandName Get-CIMInstance -MockWith { [PSCustomObject]@{ Name = "FakeService"; PathName = "HappyPath"; } } -ModuleName $moduleForMock Get-WindowsServiceApplicationName "$fakeServiceName" | Should -Be "HappyPath" Assert-MockCalled -CommandName Get-CIMInstance -Times 1 -Exactly -Scope It -ModuleName $moduleForMock Assert-MockCalled -CommandName Write-Warning -Times 0 -Exactly -Scope It -ModuleName $moduleForMock } } }