1

我有一个 PowerShell 脚本,它从 REST API 调用返回一个字符串。我在用

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

return $Response.ToString() 

我能够模拟请求,但我也应该能够模拟响应,以便它返回 $Response 的虚拟字符串值。目前我收到一个错误 RuntimeException: You cannot call a method on an null-valued expression。

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

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

有什么想法吗?

4

1 回答 1

0

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

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'
    }
}
于 2022-03-02T13:13:37.237 回答