我有一个PowerShell .ps1文件,其中包含脚本顶部的函数,随后是调用这些函数的不同命令。我正在使用Pester来测试我的脚本文件。在ps1脚本中模拟一个函数
如何模拟PowerShell .ps1脚本中的函数?
我试过嘲笑函数,但得到一个错误说“找不到命令”。
我也尝试在describe块中添加一个空的“dummy”函数。这不会给我上面的错误,但它不会正确地模拟脚本中的函数。
我有两个文件。一个持有测试,另一个持有功能和调用功能。下面是两个例子:
File1.ps1
Function Backup-Directory([switch]$IsError)
{
If($IsError)
{
Write-Error "Error"
Exit 1
}
}
Backup-Directory $true
File2.Tests.ps1
$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 Backup-Directory -Exactly 1 -ParameterFilter {
$IsError -eq $true
}
}
It "Writes error message." {
Assert-MockCalled Write-Error -Exactly 1 -ParameterFilter {
$Message -eq "Error"
}
}
It "Exits with an error." {
$hasSucceeded | Should be $false
}
}
}
我们至少需要更多的信息,可能还需要查看代码。您想要模拟的功能与您使用pester测试的同一个文件中? – EBGreen