Functions/Disconnect-ExchangeOnline.Tests.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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
        }
    }
}