我有一个 PowerShell .ps1 文件,其中包含脚本顶部的函数,后跟调用这些函数的不同命令。我正在使用 Pester 对我的脚本文件进行单元测试。
如何模拟 PowerShell .ps1 脚本中的函数?
我曾尝试模拟该函数,但收到一条错误消息,提示“找不到命令”。
我还尝试在描述块中添加一个空的“虚拟”函数。这不会给我上述错误,但它没有正确地模拟脚本中的函数。
我有两个文件。一个保存测试,另一个保存函数和对函数的调用。下面是两个例子:
Function Backup-Directory([switch]$IsError)
{
If($IsError)
{
Write-Error "Error"
Exit 1
}
}
Backup-Directory $true
Run Code Online (Sandbox Code Playgroud)
$here = (Split-Path -Parent $MyInvocation.MyCommand.Path) -replace '\\test', '\main'
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
$productionFile = "$here\$sut"
Describe "File1" {
Context "When the Back-Directory outputs an error." {
# Arrange
Mock Back-Directory { }
Mock Write-Error
# Act
& $productionFile
$hasSucceeded = $?
# Assert
It "Calls Backup-Directory" {
Assert-MockCalled …Run Code Online (Sandbox Code Playgroud)