需要PowerShell功能和模块的一些帮助

时间:2018-01-31 16:31:17

标签: powershell pester

我正在使用这个模块:

Function Get-BuildVersion {
param(
    [string] $MajorMinorVersion,
    [int] $BuildCounter,
    [int] $Offset=30,
    [string] $Suffix = "-hotfix"
 )

return "$MajorMinorVersion.$BuildCounter"
}

Export-ModuleMember -Function @(
"Get-BuildVersion"
)

我正在使用此Pester脚本进行测试:

$here = Convert-Path $PSScriptRoot
Import-Module $here\BuildNumber -Force

InModuleScope BuildNumber {

Describe "Get-BuildVersion is triggered" {
    $testCases = @(
        @{ MajorMinorVersion = "1.0"; BuildCounter = 0; ExpectedResult = "1.0.0" }
        @{ MajorMinorVersion = "2.0"; BuildCounter = 0; ExpectedResult = "2.0.0" }
        @{ MajorMinorVersion = "2.1"; BuildCounter = 0; ExpectedResult = "2.1.0" }
        @{ MajorMinorVersion = "2.1"; BuildCounter = 50; ExpectedResult = "2.1.50" }
        @{ MajorMinorVersion = "2.1"; BuildCounter = 50; Offset = 30; ExpectedResult = "2.1.80" }
        @{ MajorMinorVersion = "2.1"; BuildCounter = 50; Offset = 30; Suffix = "-hotfix"; ExpectedResult = "2.1.80-hotfix" }
    )

    Context "When getting build number" {
        foreach ($test in $testCases) {

            $result = Get-BuildVersion @test

            It "should return the expected version number: $($test.ExpectedResult)" {
                $result | Should Be $test.ExpectedResult
             }
         }
      }
   }
}

当我运行测试时,这是我得到的输出:

PS C:\users\Reddit\PowerShell> .\BuildNumber.Tests.ps1
Describing Get-BuildVersion is triggered
Context When getting build number
 [+] should return the expected version number: 1.0.0 60ms
 [+] should return the expected version number: 2.0.0 36ms
 [+] should return the expected version number: 2.1.0 36ms
 [+] should return the expected version number: 2.1.50 31ms
 [-] should return the expected version number: 2.1.80 45ms
   String lengths are both 6. Strings differ at index 4.
   Expected: {2.1.80}
   But was:  {2.1.50}
   ---------------^
   22:                     $result | Should Be $test.ExpectedResult
   at <ScriptBlock>, C:\users\Reddit\PowerShell\BuildNumber.Tests.ps1: line 22
 [-] should return the expected version number: 2.1.80-hotfix 74ms
   Expected string length 13 but was 6. Strings differ at index 4.
   Expected: {2.1.80-hotfix}
   But was:  {2.1.50}
   ---------------^
   22:                     $result | Should Be $test.ExpectedResult
   at <ScriptBlock>, C:\users\Reddit\PowerShell\BuildNumber.Tests.ps1: line 22

关于如何获得预期的2.1.80和2.1.80-修补程序值的任何想法?我尝试过格式化字符串,但无济于事。

我似乎无法在不抛出参数的情况下弄清楚如何传递其他变量$Offset$Suffix

1 个答案:

答案 0 :(得分:3)

如果打算让你的测试通过(作为一种测试驱动的开发练习),你需要修改你的函数,如下所示:

Function Get-BuildVersion {
param(
    [string] $MajorMinorVersion,
    [int] $BuildCounter,
    [int] $Offset=0,
    [string] $Suffix
 )

return "$MajorMinorVersion.$($BuildCounter+$Offset)$Suffix"
}

然后,您的测试应该按照当前定义的那样通过。

<强>的变化:

  • 默认值$Offset为0,除非被提供的值覆盖。
  • $Suffix没有默认值,因此默认为空。
  • 已修改返回的字符串,以在其输出中包含这两个参数。

此外,Return关键字在技术上是多余的,您可以将其删除。