2

我有我正在使用的这个模块:

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-hotfix 值的任何想法?我尝试格式化字符串但无济于事。

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

4

1 回答 1

2

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

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

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

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

变化:

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

仅供参考,这里的Return关键字在技术上是多余的,您可以将其删除。

于 2018-01-31T17:19:33.390 回答