【问题标题】:How to mock with pester如何用纠缠嘲笑
【发布时间】:2021-11-23 17:21:22
【问题描述】:

我想模拟 Get-ChildItem 的结果,但不断遇到问题。如何在 Pester 中模拟?

It 'Test get latest version' {
        Mock -CommandName 'Test-Path' –MockWith {
            return $true  
        }
        Mock -CommandName 'Get-ChildItem' –MockWith {
            $MockedListOfDirectories = `
            'test_1.0.1.1', `
            'test_1.1.10.5', `
            'test_1.1.10.1', `
            'test_1.2.18.1', `
            'test_1.4.7.0'
        return $MockedListOfDirectories
    }
            
}

测试的输出:

PSInvalidCastException: Cannot convert the "â€MockWith {
             return True
         }
         Mock -CommandName 'Get-ChildItem' â€MockWith" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
 ArgumentTransformationMetadataException: 
Cannot convert the "â€MockWith {
             return True
         }
         Mock -CommandName 'Get-ChildItem' â€MockWith" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
 ParameterBindingArgumentTransformationException: Cannot process argument transformation on parameter 'MockWith'. Cannot convert the "â€MockWith {
             return True
         }
         Mock -CommandName 'Get-ChildItem' â€MockWith" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
 at <ScriptBlock>, C:\my\path\to\file.ps1:8

【问题讨论】:

    标签: powershell pester


    【解决方案1】:

    您看到的错误似乎是因为-MockWith 使用的是 em-dash 而不是破折号。如果您从网页复制了示例,有时可能会发生这种情况。

    确保破折号不是 em-dash 并且您的代码对我来说可以正常工作,但要使其成为一个完整的测试,您需要实际进行一些测试,然后调用您的 Mocks,例如:

    Describe 'tests' {
    
        It 'Test get latest version' {
    
            Mock -CommandName 'Test-Path' -MockWith {
                return $true  
            }
    
            Mock -CommandName 'Get-ChildItem' -MockWith {
                $MockedListOfDirectories = `
                    'test_1.0.1.1', `
                    'test_1.1.10.5', `
                    'test_1.1.10.1', `
                    'test_1.2.18.1', `
                    'test_1.4.7.0'
                return $MockedListOfDirectories
            }
    
            Test-Path -Path 'fakepath' | Should -Be $true
         
            Get-ChildItem | Should -Contain 'test_1.1.10.5'
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-04-10
      • 1970-01-01
      • 2014-10-27
      • 2016-10-02
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 2019-02-15
      相关资源
      最近更新 更多