代码之家  ›  专栏  ›  技术社区  ›  Fairy

自身功能的输出测试

  •  -1
  • Fairy  · 技术社区  · 10 年前

    我有一个返回配置文件内容的函数:

    function Get-VA.Settings {
    <#
    .SYNOPSIS
    Fetches settings from a XML file
    .DESCRIPTION
    Fetches settings from a XML file and outputs a XML Object
    .EXAMPLE
    Get-VA.Settings -path <path-to-config-file> -Rollback <path-to-rollback-file>
    #>
      Param (
        [Parameter(Mandatory=$true,Position=0)]
        [string]$path,
        [Parameter(Mandatory=$true,Position=1)]
        [string]$Rollback
      )
      try {
        [xml]$config = Get-Content -Path $path
        Write-Output -InputObject $config
      } catch {
        Write-VA.EventLog -Message ("Could not load Configuration File: `r`n" + $Error) -Id 11 -type Error
        Invoke-VA.Rollback -Path $($Rollback)
      }
    }
    

    现在我在Pester中做了一个测试,它只是检查函数是否真的返回了什么:

    Import-Module ($PSScriptRoot + "\utility.psm1")
    Describe "Settings Module" {
      InModuleScope utility {
        Context "Get-VA.Settings" {
          It "should have Help and Examples" {
            $helpinfo = Get-Help Get-VA.Settings
            $helpinfo.examples | should not BeNullOrEmpty # should have examples
            $helpinfo.details | should not BeNullOrEmpty # should have Details
            $helpinfo.description | Should not BeNullOrEmpty # Should have a Description for the Function
          }
    
          It "should fail safely on read Error" {
            Mock Get-Content {throw}
            Mock Write-VA.EventLog { }
            Mock Invoke-VA.Rollback { }
            Get-VA.Settings -path "1" -Rollback "1"
            Assert-MockCalled Invoke-VA.Rollback -Times 1
          }
    
          It "should return a value" {
            Set-Content -Value "<xml><foo>bar</foo></xml>" -Path "settings-test.ps1" 
            Get-VA.Settings -path .\settings-test.ps1 -Rollback "1" | should not BeNullOrEmpty
            Remove-Item "settings-test.ps1"
          }
        }
      }
    }
    

    现在,无论我如何输出配置设置,我似乎都无法通过Pester的测试,即使功能正常运行也很困难。

    [-]应返回值18ms
    应为:值不能为空
    获取ConfigSettings-路径.\settings测试。ps1-回滚“1”|不应为NullOrEmpty

    我错过了什么吗?那么如何正确处理函数输出?

    1 回复  |  直到 10 年前
        1
  •  2
  •   user4003407    10 年前
    Get-Help Context
    

    在上下文范围的末尾移除上下文内定义的任何模型,

    自从 It "should fail safely on read Error" (1) 和 It "should return a value" (2) 属于同一个 Context Mock Get-Content {throw} (1)中的定义在(2)中仍然有效,因此 Get-VA.Settings 不呼叫 Get-Content cmdlet,但改为调用mock。

    推荐文章