DEV Community

Discussion on: Unit testing in PowerShell, introduction to Pester

Collapse
shengeveld profile image
shengeveld

Hi Olivier,

Thanks for the post. I do still have a scenario that I can't get to work.

function Get-ResourceGroupName {
    param (
        $someParameter
    )
    [...]
    return (Get-AzResource -name $storageAccountName).ResourceGroupName
}

The test is in another file:

Import-Module "$here/../../../test/utility.psm1" 

Describe 'Utility Unit Tests' -Tag 'unit' {
It " Retrieves storage context for a given storage account" {

        function Get-AzResource($name) { 
            $KeyObject = [PSCustomObject]@{
                ResourceGroupName = "RG100-O"
            }
            Return $KeyObject
        } 

        Get-ResourceGroupName -someParameter "https://bla.blob.core.windows.net/blobcontainer/testfile.txt" `
            | Should -Be "RG100-O"
    }
}

When running this test, I get the error that my Azure credentials have not been set, indicating the function call in the other function was not mocked. Hence, the scoping solution does not seem to have the desired effect.

Do you know how to solve this?

Collapse
shengeveld profile image
shengeveld

Solved!

The issue seemed to be session related. When I define the Get-AzResource function in the BeforeAll, it works like a charm.


BeforeAll {
    function Get-AzResource($name) { 
        $KeyObject = [PSCustomObject]@{
            ResourceGroupName = "RG100-O"
        }
        Return $KeyObject
    } 
}

Describe 'Utility Unit Tests' -Tag 'unit' {

    It " Retrieves storage context for a given storage account" {