Functions/Connect-AzureADAdminAccount.Tests.ps1

describe "BitTitan.Runbooks.AzureAD/Connect-AzureADAdminAccount" -Tag "module", "unit" {

    # Import the function to test
    . "$($PSScriptRoot)\Connect-AzureADAdminAccount.ps1"

    # Declare external functions and mocks
    function Connect-AzureAD {
        param ([PSCredential]$Credential)
    }

    context "when there are no issues" {
        # Declare mocks
        mock Connect-AzureAD {}

        it "connects to Azure AD with the provided username and password" {
            # Call the function
            $output = Connect-AzureADAdminAccount -Username "username" -Password ("password" | ConvertTo-SecureString -AsPlainText -Force)

            # Verify the mocks
            Assert-MockCalled Connect-AzureAD -Times 1 -Exactly -ParameterFilter {
                $Credential.Username -eq "username" -and $Credential.GetNetworkCredential().Password -eq "password"
            } -Scope it

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

        it "connects to Azure AD with the provided endpoint" {
            # Mock the endpoint
            $endpoint = [PSCustomObject]@{
                Credential = [PSCredential]::new("username", ("password" | ConvertTo-SecureString -AsPlainText -Force))
            }

            # Call the function
            $output = Connect-AzureADAdminAccount -Endpoint $endpoint

            # Verify the mocks
            Assert-MockCalled Connect-AzureAD -Times 1 -Exactly -ParameterFilter {
                $Credential.Username -eq "username" -and $Credential.GetNetworkCredential().Password -eq "password"
            } -Scope it

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

    context "when there is an exception while connecting to Azure AD" {

        # Mock Connect-AzureAD
        mock Connect-AzureAD {
            throw "throws exception"
        }

        it "fails to connect to Azure AD and outputs an error message" {
            # Call the function
            $output = Connect-AzureADAdminAccount -Username "username" -Password ("password" | ConvertTo-SecureString -AsPlainText -Force) `
                -ErrorAction SilentlyContinue -ErrorVariable errorVariable

            # Verify the mocks
            Assert-MockCalled Connect-AzureAD -Times 1 -Exactly -ParameterFilter {
                $Credential.Username -eq "username" -and $Credential.GetNetworkCredential().Password -eq "password"
            } -Scope it

            # Verify the output
            $errorVariable | Should Not BeNullOrEmpty
            $output | Should Be $false
        }
    }
}