I have a PowerShell script that returns a string from a REST API call. I am using
$Response = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body -ContentType 'application/x-www-form-urlencoded'
return $Response.ToString()
I am able to mock the request but I should also be able to mock the response so that it returns a dummy string value for $Response. Currently I get an error RuntimeException: You cannot call a method on a null-valued expression.
I have tried the below code as a response but i get the same error.
Mock Invoke-RestMethod -MockWith{return "abc"}
Any thoughts?
I can't see any issue with what you're trying to do. This works for me:
BeforeAll {
function Invoke-API ($URI, $Body) {
$Response = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body -ContentType 'application/x-www-form-urlencoded'
return $Response.ToString()
}
}
Describe 'Tests' {
BeforeAll {
Mock Invoke-RestMethod { return 'abc' }
}
It 'Should return a response' {
Invoke-API -Uri 'http://fake.url' -Body 'test' | Should -Be 'abc'
}
}