I have a Powershell 5.1 module like this:
function CheckEventViewerForErrors(
[string] $logName,
[string] $logSource,
[System.DateTime] $dateGreaterThanFilter
) {
try {
$logs = Get-EventLog -LogName $logName -Source $logSource
$errorLogs = $logs | Where-Object {
($_.TimeGenerated -gt $dateGreaterThanFilter) `
-and `
($_.EntryType -eq 'Error')
}
if ($null -ne $errorLogs) {
return $true
}
return $false
}
catch {
return $true
}
}
Export-ModuleMember -Function "*"
Which I want to test using Pester 3.4.0 like below, but the mock isn't being called when I use the commented-out parameter filter.
Describe 'CheckEventViewerForErrors' {
$logName = 'Application'
$logSource = "Pester"
$time = Get-Date
$cmdToMock = 'Get-EventLog'
$moduleName = $module.Name
Context 'Tests using mocks' {
# $paramFilter = { ($LogName -eq $logSource) -and ($LogName -eq $logName) }
It 'returns $false when there are entries for the source but no errors' {
Mock `
-ModuleName $moduleName `
-CommandName $cmdToMock `
-MockWith { return @{ TimeGenerated = $time; EntryType = 'Error' } }
# -ParameterFilter $paramFilter
$expected = $false
[bool] $actual = CheckEventViewerForErrors `
-logName $logName `
-logSource $logSource `
-dateGreaterThanFilter $time
Assert-MockCalled -Module $moduleName -CommandName $cmdToMock # -ParameterFilter $paramFilter
$actual | Should Be $expected
}
}
}
What's wrong with this code?. How can I mock the use of Get-EventLog in the function exported?
This message is returned by the above test:
Expected Get-EventLog to be called at least 1 times but was called 0 times
There is an error in your Parameter Filter, you are filtering for LogName twice, but with different variables (hence it doesn't end up resulting in a matched use of Get-EventLog
in the script):
$paramFilter = { ($LogName -eq $logSource) -and ($LogName -eq $logName) }
If I change it to this, you code works for me:
$paramFilter = { ($LogSource -eq $logSource) -and ($LogName -eq $logName) }