在 Pester 中模拟 REST API 的响应

Mocking Response of a REST API in Pester

我有一个 PowerShell 脚本,其中 returns 来自 REST API 调用的字符串。我正在使用

$Response = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body -ContentType 'application/x-www-form-urlencoded'

return $Response.ToString() 

我能够模拟请求,但我也应该能够模拟响应,以便它 returns $Response 的虚拟字符串值。目前我得到一个错误 RuntimeException: 你不能在空值表达式上调用方法。

我尝试了下面的代码作为响应,但我得到了同样的错误。

Mock Invoke-RestMethod -MockWith{return "abc"}

有什么想法吗?

我看不出你的尝试有任何问题。这对我有用:

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