Zoltaire
Zoltaire

Reputation: 21

Mocking Response of a REST API in Pester

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?

Upvotes: 1

Views: 762

Answers (2)

Jasper
Jasper

Reputation: 1

I had this situation when I used the Invoke-RestMethod in a Module. I wanted to mock it but it didn't. Had to specify the module name of my own module (not the PowerShell.Utility) and then it worked.

Edit:

File to test: TestModule.psm1

Pester file: TestModule.Tests.ps1 containing:

$moduleName = "TestModule" 
Mock -ModuleName $moduleName -CommandName Invoke-RestMethod -MockWith {
   throw $exceptionObj  
}

Upvotes: 0

Mark Wragg
Mark Wragg

Reputation: 23395

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'
    }
}

Upvotes: 0

Related Questions