Pester 中 REST API 的模拟响应

发布于 2025-01-10 05:04:08 字数 436 浏览 5 评论 0原文

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

$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"}

有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

因为看清所以看轻 2025-01-17 05:04:08

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

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

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'
    }
}
秋凉 2025-01-17 05:04:08

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

编辑:

要测试的文件:TestModule.psm1

Pester 文件:TestModule.Tests.ps1 包含:

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

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  
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文