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-AzStorageBlobcmdlet的输入要求-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
}
}
}

最新更新