脚本在 Pester 测试中返回$null的问题,而它不应该



所以我在PowerShell中遇到了一些问题我为一个关于害虫测试的课堂项目写了一个简单的脚本看起来像这个

param ([Parameter(Mandatory, ValueFromPipeline = $true)]$FN, [Parameter(Mandatory)]$OP, [Parameter()]$SN)
$solution
try {
if ($OP -eq '+') {
$solution = ([long]($FN) + [long]($SN))

}
elseif ($OP -eq '-') {
$solution = ([long]($FN) - [long]($SN))

}
elseif ($OP -eq '*') {
$solution = ([long]($FN) * [long]($SN))

}
elseif ($OP -eq '/') {
if ($SecondNumber -eq 0) {
$solution = "Cannot divide by 0";
}
$solution = ([long]($FN) / [long]($SN))

}
elseif ($OP -eq 'V') {
$solution = ([math]::Sqrt($FN))

}

else {
$solution = "Not a valid operator"
}

}
catch {
Write-Output "An error occured"
}
return $solution

现在,这一切都很好,当我进入控制台并在ooutput进入变量的情况下运行它时,它也很好。

PS C:PowerShellProject> $test = .Script.ps1 1 + 1
PS C:PowerShellProject> $test
2

但当我运行这个害虫测试时

Describe "Test for Script.ps1" {
Context "Testing calculations" {
It "+ test" {
$plus = .Test.ps1 -FN 2 -OP + -SN 2
$plus | Should -Be 4
}
}
}

它返回以下

PS C:PowerShellProject> Invoke-Pester .Test.ps1
Starting discovery in 1 files.
Discovery found 1 tests in 15ms.
Running tests.
[-] Test for Script.ps1.Testing calculations.+ test 18ms (16ms|2ms)
Expected 4, but got $null.
at $plus | Should -Be 4, C:PowerShellProjectTest.ps1:6
at <ScriptBlock>, C:PowerShellProjectTest.ps1:6
[-] Context Test for Script.ps1.Testing calculations failed
InvalidOperationException: Collection was modified; enumeration operation may not execute.
Tests completed in 156ms
Tests Passed: 0, Failed: 1, Skipped: 0 NotRun: 1
BeforeAll  AfterAll failed: 1
- Test for Script.ps1.Testing calculations

我对Powershell还很陌生,所以我可能在这里犯了一个愚蠢的错误。

也许有人可以把我重定向到另一个有类似问题的问题上,或者给我一个问题的解决方案。这真的很有帮助,因为我已经为此伤透了脑筋好几个小时了,这真的开始让我恼火了

问题是函数开头的这一行:

$solution

这并没有像您预期的那样声明变量,但由于PowerShell的隐式输出行为,它实际上输出变量。输出为$null,因为变量尚未定义。

要真正定义变量,您必须指定一个值:

$solution = 0

稍后,当您执行return $solution时,实际上是在向输出流添加另一个值,当捕获到变量时,该值将是数组@($null, 2)

证明:

$plus = .Test.ps1 -FN 2 -OP + -SN 2            
Write-Host $plus.GetType().Name

这将打印Object[],尽管我们期望int

在PowerShell中,通常不使用return语句,除非您希望提前退出函数。return $solution实际上只是的快捷方式

$solution  # implicit output
return     # exit from function

您的Pester测试脚本中还有另一个问题,您调用了错误的脚本。应该是:

$plus = .Script.ps1 -FN 2 -OP + -SN 2

相关内容

最新更新