我想模擬 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 "a€MockWith {
return True
}
Mock -CommandName 'Get-ChildItem' a€MockWith" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
ArgumentTransformationMetadataException:
Cannot convert the "a€MockWith {
return True
}
Mock -CommandName 'Get-ChildItem' a€MockWith" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
ParameterBindingArgumentTransformationException: Cannot process argument transformation on parameter 'MockWith'. Cannot convert the "a€MockWith {
return True
}
Mock -CommandName 'Get-ChildItem' a€MockWith" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
at <ScriptBlock>, C:\my\path\to\file.ps1:8
uj5u.com熱心網友回復:
看起來您看到的錯誤是因為-MockWith使用的是破折號而不是破折號。如果您從網頁中復制了示例,有時會發生這種情況。
確保破折號不是 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'
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366206.html
