Get-AzureBlobStorage 的纠缠单元测试

Pester Unit Test for Get-AzureBlobStorage

我正在尝试在 Powershell 中为一个简单的 Azure 函数编写一个单元

function Get-AzureBlobStorage {
    param (
        [Parameter(Mandatory)]
        [string]$ContainerName,
        [Parameter(Mandatory)]
        [string]$Blob,
        [Parameter(Mandatory)]
        $Context
    )
    try {
        return (Get-AzStorageBlob -Container $ContainerName -Context $Context -Blob $Blob)
    }
    catch {
        Write-Error "Blobs in Container [$ContainerName] not found"

    }

Unit test

   Context 'Get-AzureBlobStorage' {
        It 'Should be able to get details to Blob Storage account without any errors' {
                $ContainerName = 'test'
                $Blob="test-rg"
                $Context = "test"
                Mock Get-AzStorageBlob { } -ModuleName $moduleName
                Get-AzureBlobStorage -ContainerName $ContainerName -Blob $Blob -Context $Context -ErrorAction SilentlyContinue -ErrorVariable errors
                $errors.Count | Should -Be 0
            }
}

但我无法让它工作。我收到以下错误,

Cannot process argument transformation on parameter 'Context'. Cannot convert the "test" value of type "System.String" to type "Microsoft.Azure.Commands.Common.Authentication.Abstractions.IStorageContext". 

我的问题是如何获取上下文这样的值。我还有其他几个函数,其中一个参数总是一些复杂的对象。为此类功能编写单元测试的最佳方法是什么

您的问题是因为 Get-AzStorageBlob cmdlet 的输入需要 -Context 的特定类型的对象。您可以通过使用 Mock-RemoveParameterType.

让 Pester 删除输入中的强类型

以下是我测试您的功能的方法:

Describe 'Tests' {

    Context 'Get-AzureBlobStorage returns blob' {
        
        BeforeAll {
            Mock Get-AzStorageBlob {} -RemoveParameterType Context
        }

        It 'Should be able to get details to Blob Storage account without any errors' {

            $ContainerName = 'test'
            $Blob = "test-rg"
            $Context = "test"

            Get-AzureBlobStorage -ContainerName $ContainerName -Blob $Blob -Context $Context -ErrorVariable errors
            Assert-MockCalled Get-AzStorageBlob
        }
    }

    Context 'Get-AzureBlobStorage returns error' {

        BeforeAll {
            Mock Get-AzStorageBlob { throw 'Error' } -RemoveParameterType Context
            Mock Write-Error { }
        }

        It 'Should return an error via Write-Error' {

            $ContainerName = 'test'
            $Blob = "test-rg"
            $Context = "test"

            Get-AzureBlobStorage -ContainerName $ContainerName -Blob $Blob -Context $Context
            Assert-MockCalled Write-Error -Times 1 -Exactly
        }
    }
}