简体   繁体   English

如何用纠缠嘲笑

[英]How to mock with pester

I want to mock the results from Get-ChildItem but keep getting issues.我想模拟 Get-ChildItem 的结果,但不断遇到问题。 How do I mock in Pester?我如何在 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
    }
            
}

The output from the tests:测试中的 output:

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

It looks like the error you are seeing is because -MockWith is using an em-dash instead of a dash.看起来您看到的错误是因为-MockWith使用的是 em-dash 而不是破折号。 This can happen sometimes if you've copied an example from a webpage.如果您从网页复制了示例,有时可能会发生这种情况。

Ensuring the dashes are non em-dash and your code works fine for me, although for it to be a complete test you need to actually do some testing that then invokes your Mocks, for example:确保破折号不是 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'
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM