From 8068bb371173e05eb5ac182a5b53eb2c6c59a7e4 Mon Sep 17 00:00:00 2001 From: Dave Wyatt Date: Wed, 25 Jun 2014 18:07:52 -0400 Subject: [PATCH] ParameterFilter fixes The script block passed to the -ParameterFilter parameters on Mock and Assert-MockCalled is now executed in the test script's scope. To prevent errors when the parameter filter is being evaluated in some cases, Strict Mode is disabled within that block (but left alone otherwise).s --- Functions/Mock.Tests.ps1 | 28 ++++++++++++++++++++++++++++ Functions/Mock.ps1 | 7 ++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/Functions/Mock.Tests.ps1 b/Functions/Mock.Tests.ps1 index 01de512ef..a39bc47f4 100644 --- a/Functions/Mock.Tests.ps1 +++ b/Functions/Mock.Tests.ps1 @@ -247,6 +247,34 @@ Describe "When calling Mock on non-existing function" { } } +Describe 'When calling Mock, StrictMode is enabled, and variables are used in the ParameterFilter' { + Set-StrictMode -Version Latest + + $result = $null + $testValue = 'test' + + try + { + Mock FunctionUnderTest { 'I am the mock' } -ParameterFilter { $param1 -eq $testValue } + } + catch + { + $result = $_ + } + + It 'Does not throw an error when testing the parameter filter' { + $result | Should Be $null + } + + It 'Calls the mock properly' { + FunctionUnderTest $testValue | Should Be 'I am the mock' + } + + It 'Properly asserts the mock was called when there is a variable in the parameter filter' { + Assert-MockCalled FunctionUnderTest -Exactly 1 -ParameterFilter { $param1 -eq $testValue } + } +} + Describe "When calling Mock on existing function without matching bound params" { Mock FunctionUnderTest {return "fake results"} -parameterFilter {$param1 -eq "test"} diff --git a/Functions/Mock.ps1 b/Functions/Mock.ps1 index b81e5cfc4..e771d3f2a 100644 --- a/Functions/Mock.ps1 +++ b/Functions/Mock.ps1 @@ -687,8 +687,9 @@ function Test-ParameterFilter if ($null -eq $ArgumentList) { $ArgumentList = @() } if ($null -eq $CmdletBinding) { $CmdletBinding = '' } if ($null -eq $ParamBlock) { $ParamBlock = '' } - - $cmd = [scriptblock]::Create("$CmdletBinding `r`n param ( $ParamBlock ) `r`n$ScriptBlock") - + + $cmd = [scriptblock]::Create("$CmdletBinding param ( $ParamBlock ) Set-StrictMode -Off; $ScriptBlock") + Set-ScriptBlockScope -ScriptBlock $cmd -SessionState $pester.SessionState + & $cmd @BoundParameters @ArgumentList } \ No newline at end of file