Adam
Adam

Reputation: 4178

Access External Variable from with-in Mock Script Block (Pester)

Pretend I have a function like...

function Get-Something {
  return Get-DogShit
}

...in my Pester test script...

$var = 1

Mock 'Get-Dogshit' { return $var }

it 'should return true' {
  Get-Something | should $var
}

This doesn't work, but you see what I'm trying to do here? I want to get the value from a local variable into a MOCK script block. I want to avoid hard coding the return value in the mock and the expected result in the it-block. Any ideas on how I can achieve this?

Upvotes: 9

Views: 1619

Answers (2)

wekempf
wekempf

Reputation: 2788

I had this problem myself, and script scope didn't work and I didn't care to use global scope. A bit of research shows how you can use closures for this.

$var = 1

Mock 'Get-Dogshit' { return $var }.GetNewClosure()

it 'should return true' {
  Get-Something | Should be $var
}

Upvotes: 6

G42
G42

Reputation: 10019

Wasn't sure if it would work as not messed with pester before but apparently it follows the same scope rules as standard PowerShell.

So $script:var = 1, and the brute-force $global:var = 1 if it doesn't or if you need to call it from outside the script scope.

Upvotes: 1

Related Questions