【问题标题】:Mocking Response of a REST API in Pester在 Pester 中模拟 REST API 的响应
【发布时间】:2023-02-07 22:05:01
【问题描述】:

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

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

return $Response.ToString() 

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

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

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

有什么想法吗?

【问题讨论】:

    标签: unit-testing pester powershell-7.2 pester-5


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我在模块中使用 Invoke-RestMethod 时遇到过这种情况。我想嘲笑它,但它没有。必须指定我自己的模块(不是 PowerShell.Utility)的模块名称,然后它才能工作。

      【讨论】:

        猜你喜欢
        • 2020-02-04
        • 2018-04-21
        • 1970-01-01
        • 2018-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多