Public/InstallHelpers/Install.Service.Functions.Tests.ps1

#Requires -Version 5.0
#Requires -Modules @{ ModuleName="Pester"; ModuleVersion="3.4.0" }
$ErrorActionPreference = "Stop";
Set-StrictMode -Version 'Latest'

$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.ps1', '.psm1'
Import-Module "$PSScriptRoot\$sut" -Force


Describe 'DetermineIfServiceInstalled' -Tags 'Unit' {
    It 'returns false when service not present' {
        # Arrange
        [string] $expected = $false
        [string] $serviceName = 'NonExistentService'
        # Act
        [bool] $actual = DetermineIfServiceInstalled -svcName $serviceName 
        # Assert
        $actual | Should Be $expected
    }
    It 'returns true when service present' {
        # Arrange
        [string] $expected = $true
        [string] $serviceName = 'Windows Event Log'
        # Act
        [bool] $actual = DetermineIfServiceInstalled -svcName $serviceName 
        # Assert
        $actual | Should Be $expected
    }
}


Describe 'StopService' -Tags 'Unit' {
    It 'returns false when service not present' {
        # Arrange
        [string] $expected = $false
        [string] $serviceName = 'NonExistentService'
        # Act
        [bool] $actual = DetermineIfServiceInstalled -svcName $serviceName 
        # Assert
        $actual | Should Be $expected
    }
    It 'returns true when service present' {
        # Arrange
        [string] $expected = $true
        [string] $serviceName = 'Windows Event Log'
        # Act
        [bool] $actual = DetermineIfServiceInstalled -svcName $serviceName 
        # Assert
        $actual | Should Be $expected
    }
}


# NOTE: This test depends on the presence of an EXE/installer
# DANGER: This test will remove a specified service from your machine
Describe 'InstallService' -Tags 'Integration' {
    # Arrange
    [string] $expected = 'Stopped'
    [string] $serviceName = 'TrainingNotifier_Test' 

    [string] $pathToExe = "$PSScriptRoot\Fixtures\TN.Service\AppService.exe"
    # Act
    InstallService -svcName $serviceName -pathToExe $pathToExe

    [System.ServiceProcess.ServiceController] $svc = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
    [string] $actual = if ($null -ne $svc) { $svc.Status } else { '' }

    # Assert
    It 'returns expected' {
        $actual | Should Be $expected
    }
}