[英]Dealing with Arrays in Powershell (testing with Pester)
我在理解实现此过程的方式时遇到了一些麻烦。 我想获得总分,以便如果测试成功通过或失败,可以将其添加到数组中。 该数组将计入长度。
这是我的代码作为示例:
#This stores the array of the number of passed and failed test
$passed = @()
$failed = @()
Describe "Template Syntax" {
It "Has a JSON template" {
$fileLocation = "$here\azuredeploy.json"
$fileCheck = $fileLocation | Test-Path
if ($fileCheck -eq $true) { $passed = $passed + 1
Write-Host "1st file exist " }
if ($fileCheck -eq $false) { $failed = $failed + 1
Write-Host "1st file does exist" }
}
It "Has a parameters file" {
$fileLocation ="$here\azuredeploy.parameters*.json"
$fileCheck = $fileLocation | Test-Path
if ($fileCheck -eq $true) { $passed = $passed + 1;
Write-Host "2nd file exist "}
if ($fileCheck -eq $false) { $failed = $failed + 1
Write-Host "2nd file does exist" }
}
PrintArgs
}
function PrintArgs(){
Write-Host -ForegroundColor yellow "Passed: $($passed.Length) Failed: $($failed.Length)"
}
我可以通过其他方式或其他方式来实现这一目标吗? 我知道paster会自动执行此操作,但是,我想使用Powershell脚本进行测试。
查看您的代码,您不需要数组来计算分数。 无需将$passed
和$failed
定义为数组,只需将它们设置为起始值为0的整数计数器
$passed = $failed = 0
然后,您只需执行以下操作, 而不是调用函数PrintArgs()
Write-Host -ForegroundColor yellow "Passed: $passed Failed: $failed"
顺便说一句,要增加一个计数器,您可以简单地执行$passed++
而不是$passed = $passed + 1
如果您确实坚持使用数组,则可以将$passed = $passed + 1
更改为$passed += $true
。 这样,您可以向数组中添加一个值为$ true的新元素(或者您觉得更合适的任何元素)。
除非您包含Should
断言,否则您的Pester测试并不是真正的Pester测试。 我认为您应该按照以下方式重写测试:
Describe "Template Syntax" {
$fileLocation = "$here\azuredeploy.json"
$fileCheck = $fileLocation | Test-Path
It "Has a JSON template" {
$fileCheck | Should -Be $true
}
$fileLocation ="$here\azuredeploy.parameters*.json"
$fileCheck = $fileLocation | Test-Path
It "Has a parameters file" {
$fileCheck | Should -Be $true
}
}
如果随后使用Invoke-Pester
运行此程序,则会在最后自动获得通过和失败测试计数的摘要。 如果需要访问这些值,则可以使用-PassThru
将它们返回到变量。 例如:
$Results = Invoke-Pester .\your.tests.ps1 -PassThru
然后,您可以获取通过和失败测试的次数,如下所示:
$Results.PassedCount
$Results.FailedCount
如果您确实想使用自己的计数器(这意味着要维护许多不必要的逻辑),则可以执行以下操作:
$Passed = 0
$Failed = 0
Describe "Template Syntax" {
$fileLocation = "$here\azuredeploy.json"
$fileCheck = $fileLocation | Test-Path
It "Has a JSON template" {
$fileCheck | Should -Be $true
}
if ($fileCheck -eq $true) { $Passed++ } else { $Failed++ }
$fileLocation ="$here\azuredeploy.parameters*.json"
$fileCheck = $fileLocation | Test-Path
It "Has a parameters file" {
$fileCheck | Should -Be $true
}
if ($fileCheck -eq $true) { $Passed++ } else { $Failed++ }
Write-Host -ForegroundColor yellow "Passed: $Passed Failed: $Failed"
}
请注意, Describe
块充当一种脚本作用域,因此您必须在Describe
打印$Passed
和$Failed
的值才能获取这些值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.