0

I'm trying to write unit tests for Powershell function which use Write-Host function.

I mocked Write-Host and trying to assert that mock has been called with a valid argument.

Mock Write-Host -Verifiable

It "Open Db connection" {
    Open-Db-Connection -connectionString 'test'

    Assert-MockCalled Write-Host -ParameterFilter {
        $Object | Should Be "Connection to $dataSourceName-$databaseName established"
    }

    Assert-MockCalled Write-Host -ParameterFilter {
        $Object -eq "Connection to $dataSourceName-$databaseName established"
    }
}   

When I'm using -eq operator id works fine, but without a good message when actual argument not matches expected. I'm trying to use Should Be construction which prints a good error message. But for me, it only works in case if actually does not match expected. and in case if they match it says that Write-Host was not called at all.

I start thinking that Should Be for some reason cannot be used inside ParameterFilter block, because outside of it it works perfectly.

Jorgen
  • 83
  • 1
  • 7
  • Correct, you should _not_ be using `Should` inside the `ParameterFilter` block - it's a filter clause block and should simply return either `$true`, `$false` or nothing – Mathias R. Jessen Aug 30 '19 at 14:24
  • but how should I structure my test code to verify that Write-Host was called with an argument which I expect and print an informative message in another case? because if I define mock for a specific argument it will say that function was not called instead of saying that function was called but with the wrong argument? – Jorgen Aug 30 '19 at 14:29
  • See this [post](https://stackoverflow.com/questions/57895749/how-to-get-arguments-for-calls-made-on-a-mock-in-pester-or-otherwise-generate). Many people wish that Pester gave better Assert-MockCalled error messages. – Nathan W Sep 30 '19 at 21:14

0 Answers0