Closed paraknell closed 6 years ago
Hi @mwtilton,
I had to make a small change to reproduce your error: $result = Restart-Device
becomes $result = Invoke-RestMethod -Uri "myuri"
, but once I did that I got the same result as you.
So I think the issue is that $_
refers to the "current object" in the "current pipeline" (see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-6#-3) and it resolves to a different value inside the ForEach-Object and Mock because they're using running in different pipeline contexts.
You can test this by using write-host '$_'
to write out the value of from both scopes - it'll write 200
(for example) from the ForEach-Object and an empty string (or maybe $null
) from inside the Mock body.
What you can do, is "capture" the $_
from the ForEach-Object into a named variable and then refer to that in the Mock instead of $_
. For example:
$values | ForEach-Object {
$myItem = $_ # <-- capture the current pipeline item
Context "Foreach-Object Restmethod returns $_ code" {
Mock Invoke-RestMethod {
$myItem # <-- return the captured value
}
... etc ...
That made the tests start working on my local machine.
Hope this helps.
M
oh yea I forgot to post my function
Function Restart-Device {
Invoke-RestMethod -Uri "someuri" -ContentType application/x-www-form-urlencoded -Method POST -SessionVariable WebSession -ErrorAction stop
}
If I had done that you probably wouldn't have gotten a weird initial result.
Anyways this seems to have cleaned up my issue at least for my unit testing, I'll know better once I go through some more acceptance tests. But assuming that works I should still be able to use the $_
outside of the Context "Foreach-Object Restmethod returns $_ code"
I'll update once I have this tested a little further.
Thanks for the help!
This is working fine. Closing.
1. General summary
Mocking with Foreach-Object and Invoke-Restmethod doesn't return correct result
2. Environment
Operating System, Pester version and PowerShell version:
3. Expected Behavior
4. Current Behavior
If I use the Foreach loop it will pass all tests. If I use the Foreach-Object it will fail on blocks:
It "returns $_"
It "Should not be empty"
5. Possible Solution
Not at this time
6. Context
I would like to eventually use the Begin, process and End blocks and I'm for other pipeline output in future scripts, such as
$_.filename | Should Match "c:\path\to\file"
and others. I haven't specifically tested this example but I'm assuming something similar would cause an error as well.