如何嘲笑纠缠

How to mock with pester

我想模拟 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

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

确保破折号不是 em-dash 并且你的代码对我来说工作正常,尽管要成为一个完整的测试你需要实际做一些测试然后调用你的模拟,例如:

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'
    }
}