Functions/Disconnect-ExchangeOnline.Tests.ps1

describe "BitTitan.Runbooks.ExchangeOnline/Disconnect-ExchangeOnline" -Tag "module", "unit" {

    # Import the function to test
    . "$($PSScriptRoot)\Disconnect-ExchangeOnline.ps1"

    context "when there is one session" {
        # Mock Get-PSSession
        mock Get-PSSession {
            $session = New-MockObject -Type System.Management.Automation.Runspaces.PSSession
            $session.Name = "ExchangeOnline"
            return $session
        }

        # Mock Remove-PSSession
        mock Remove-PSSession {}

        it "disconnects the session" {
            # Call the function
            $output = Disconnect-ExchangeOnline

            # Validate the mocks
            Assert-MockCalled Get-PSSession -Times 1 -Exactly -Scope it
            Assert-MockCalled Remove-PSSession -Times 1 -Exactly -ParameterFilter {
                $Session.Name -eq "ExchangeOnline"
            } -Scope it

            # Validate the output
            $output | Should Be $true
        }
    }

    context "when there are multiple sessions" {
        # Mock Get-PSSession
        mock Get-PSSession {
            $session = New-MockObject -Type System.Management.Automation.Runspaces.PSSession
            $session.Name = "ExchangeOnline"
            return @($session, $session, $session)
        }

        # Mock Remove-PSSession
        mock Remove-PSSession {}

        it "disconnects all of the sessions" {
            # Call the function
            $output = Disconnect-ExchangeOnline

            # Validate the mocks
            Assert-MockCalled Get-PSSession -Times 1 -Exactly -Scope it
            Assert-MockCalled Remove-PSSession -Times 3 -Exactly -ParameterFilter {
                $Session.Name -eq "ExchangeOnline"
            } -Scope it

            # Validate the output
            $output | Should Be $true
        }
    }

    context "when there are no sessions" {
        # Mock Get-PSSession
        mock Get-PSSession {}

        # Mock Remove-PSSession
        mock Remove-PSSession {}

        it "does not disconnect any session and outputs a warning" {
            # Call the function
            $output = Disconnect-ExchangeOnline -WarningAction SilentlyContinue `
                -WarningVariable warningVariable

            # Validate the mocks
            Assert-MockCalled Get-PSSession -Times 1 -Exactly -Scope it
            Assert-MockCalled Remove-PSSession -Times 0 -Exactly -Scope it

            # Validate the output
            $warningVariable | Should Not BeNullOrEmpty
            $output | Should Be $false
        }
    }
}