この PowerShell 関数は、特定の文字列を含まないファイルを識別します。
function GetFilesLackingItem([string]$pattern)
{
Get-ChildItem | ? { !( Select-String -pattern $pattern -path $_ ) }
}
Get-ChildItem と Select-String をモックして Pester 単体テストを作成しようとしていますが、問題が発生しました。どちらも同じように失敗する 2 つの試みを次に示します。最初のテストではモックを使用parameterFilter
して区別しますが、2 番目のテストではこれを実行するためのロジックをmockCommand
それ自体に追加します。
Describe "Tests" {
$fileList = "nameA", "nameB", "nameC", "nameD", "nameE" | % {
[pscustomobject]@{ FullName = $_; }
}
$filter = '(B|D|E)$'
Mock Get-ChildItem { return $fileList }
It "reports files that did not return a match" {
Mock Select-String { "matches found" } -param { $Path -match $filter }
Mock Select-String
$result = Get-ChildItem | ? { !(Select-String -pattern "any" -path $_) }
$result[0].FullName | Should Be "nameA"
$result[1].FullName | Should Be "nameC"
$result.Count | Should Be 2
}
It "reports files that did not return a match" {
Mock Select-String {
if ($Path -match $filter) { "matches found" } else { "" }
}
$result = Get-ChildItem | ? { !(Select-String -pattern "any" -path $_ ) }
$result[0].FullName | Should Be "nameA"
$result[1].FullName | Should Be "nameC"
$result.Count | Should Be 2
}
}
Select-String-path
パラメーターが$_.FullName
代わりになるようにテストを変更すると$_
、両方のテストに合格します。しかし、実際には(つまり、モックなしで行を実行すると)$_
、. (これは とも正しく動作し$_.FullName
ます。) したがって、実際の Select-String は、Path パラメーターの FileInfo オブジェクトの配列から FullName をマップできるようです (ただし、それを行うためのパラメーター エイリアスがあったことはわかりませんでした)。
私の質問: 元のコードをそのままにしておくことはでき$_
ますか? たとえば、$Path.FullName
どちらのモックでも機能しません。