gpt4 book ai didi

pester - 如何使用 Pester 模拟模块不可用的 cmdlet?

转载 作者:行者123 更新时间:2023-12-02 20:25:14 26 4
gpt4 key购买 nike

我正在尝试为我的 Azure 自动化 Runbook 编写 Pester 测试。 Runbook 脚本使用 Get-AutomationVariable cmdlet,我尝试通过以下方式模拟它:

mock 'Get-AutomationVariable' {return "localhost:44300"} -ParameterFilter { $name -eq "host"}

这会导致错误

CommandNotFoundException: The term 'Get-AutomationVariable' is not recognized as the name of a cmdlet, function, script file, or operable program.

Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

-ModuleName的使用参数似乎不合适,因为我是从脚本而不是模块调用该方法。尝试提供 stub 模块会导致抛出相同的错误。

. "$here\$sut" "CN=teset, OU=Test" "CN=SubCA02, OU=Test"

Get-Module -Name RunbookMock | Remove-Module
New-Module -Name RunbookMock -ScriptBlock {
function Get-AutomationVariable {
[CmdLetBinding()]
param(
[string]$Name
)

""
}
Export-ModuleMember Get-AutomationVariable
} | Import-Module -Force

describe 'Pin-Certificate' {
it 'should add an entry to the pinned certificate list'{
mock 'Get-AutomationVariable' { return "sastoken"} -ParameterFilter { $Name -eq "StorageSasToken"} -
mock 'Get-AutomationVariable' {return "localhost:44300"} -ParameterFilter { $name -eq "host"}
}
}

最佳答案

根据评论,您的代码应该可以工作。过去我只是声明了一个空函数而不是一个完整的模块。例如:

function MyScript {
Get-FakeFunction
}

Describe 'Some Tests' {

function Get-Fakefunction {}

Mock 'Get-Fakefunction' { write-output 'someresult' }

$Result = MyScript

it 'should invoke Get-FakeFunction'{
Assert-MockCalled 'Get-Fakefunction' -Times 1
}
it 'should return someresult'{
$Result | Should -Be 'someresult'
}
}

关于pester - 如何使用 Pester 模拟模块不可用的 cmdlet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50163808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com